Skip to main content
 首页 » 编程设计

python之正则表达式分组直到空格

2025年05月04日24cloudgamer

我有这样一行:

[24 Mar 2019] ABC-000 somestring-with-numbers-and-dashes - a whole bunch of text 

正则表达式是这样的:

re_header = re.compile(r'^\[(\d\d) ([A-Z][a-z][a-z]) (\d{4})\] ' 
                    + r'(ABC-\d+(?:-\d+)?)\s+' 
                    + r'(.*?)\s*$') 

现在我得到的是:

('24', 'Mar', '2019', 'ABC-000', 'somestring-with-numbers-and-dashes - a whole bunch of text') 

不过我想要的是一个由“somestring-with-numbers-and-dashes”组成的附加组,如下所示:

('24', 'Mar', '2019', 'ABC-000', 'somestring-with-numbers-and-dashes') 

'somestring-with-numbers-and-dashes' 后面的所有内容都应忽略。

我怎样才能做到这一点?

请您参考如下方法:

你可以使用

^\[(\d{2}) ([A-Z][a-z]{2}) (\d{4})\]\s*(DSA-\d+(?:-\d+)?)\s+([^\s-]+(?:-[^\s-]+)*) 

参见 regex demo (因为您的模式包含 DSA 而不是 ABC,所以我在我的模式和 regex101 的演示字符串中使用了 DSA)。

你感兴趣的部分是([^\s-]+(?:-[^\s-]+)*):

  • [^\s-]+ - 除了空格和 -
  • 之外的 1+ 个字符
  • (?:-[^\s-]+)* - - 的 0 次或多次重复,后跟除空格和 之外的任何 1+ 个字符-。