Python 正则表达式分组直到空格

Python 正则表达式分组直到空格,python,regex,Python,Regex,我有这样一句话: [24 Mar 2019] ABC-000 somestring-with-numbers-and-dashes - a whole bunch of text ('24', 'Mar', '2019', 'ABC-000', 'somestring-with-numbers-and-dashes') 正则表达式如下所示: re_header = re.compile(r'^\[(\d\d) ([A-Z][a-z][a-z]) (\d{4})\] '

我有这样一句话:

[24 Mar 2019] ABC-000 somestring-with-numbers-and-dashes - a whole bunch of text
('24', 'Mar', '2019', 'ABC-000', 'somestring-with-numbers-and-dashes')
正则表达式如下所示:

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')
不过,我想要的是一个由“带数字和破折号的字符串”组成的附加组,如下所示:

[24 Mar 2019] ABC-000 somestring-with-numbers-and-dashes - a whole bunch of text
('24', 'Mar', '2019', 'ABC-000', 'somestring-with-numbers-and-dashes')
应该忽略
'somestring-with-numbers-and-dash'
后面的所有内容

如何实现这一点?

您可以使用

^\[(\d{2}) ([A-Z][a-z]{2}) (\d{4})\]\s*(DSA-\d+(?:-\d+)?)\s+([^\s-]+(?:-[^\s-]+)*)
请参阅(由于您的模式包含
DSA
而不是
ABC
,因此我在我的模式中使用了
DSA
,并在regex101中使用了演示字符串)

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

  • [^\s-]+
    -1+除空格和
    -
  • (?:-[^\s-]+)*
    -0次或多次重复
    -
    ,后跟除空格和
    -
    以外的任何1+字符
您可以使用

^\[(\d{2}) ([A-Z][a-z]{2}) (\d{4})\]\s*(DSA-\d+(?:-\d+)?)\s+([^\s-]+(?:-[^\s-]+)*)
请参阅(由于您的模式包含
DSA
而不是
ABC
,因此我在我的模式中使用了
DSA
,并在regex101中使用了演示字符串)

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

  • [^\s-]+
    -1+除空格和
    -
  • (?:-[^\s-]+)*
    -0次或多次重复
    -
    ,后跟除空格和
    -
    以外的任何1+字符
只需将final
(.*)\s*$
更改为
([^\s]*)

注意,我必须在原始表达式中将
DSA
更改为
ABC
,以使其正常工作。

只需将final
(.*?)\s*$
更改为
([^\s]*)


注意,我必须在原始表达式中将
DSA
更改为
ABC
,以使其工作。

您可以简单地将最后一个正则表达式部分替换为

(.*?) - .*$

因此,在
-
出现之前,您可以捕获尽可能少的文本。

您可以简单地将最后一个regex部分替换为

(.*?) - .*$

因此,在
-
出现之前,您要捕获尽可能少的文本。

如果日期只包含1个数字,月份超过3个字符,则正则表达式中的其他问题,例如2019年6月9日。此外,您在正则表达式中使用了
DSA
,但它怎么能在输出中使用
ABC
?因此,为了适应这些情况,最好使用以下方法:


如果日期仅包含1个数字且月份超过3个字符,则正则表达式中的其他问题,例如2019年6月9日。此外,您在正则表达式中使用了
DSA
,但它怎么能在输出中使用
ABC
?因此,为了适应这些情况,最好使用以下方法:


将上一个正则表达式替换为
(.*)\s-.
将上一个正则表达式替换为
(.*)\s-.