正则表达式:匹配一个空格连接的单词列表,排除最后的空格

1 投票
1 回答
1478 浏览
提问于 2025-04-15 21:57

我想知道怎么匹配一个用空格分开的单词列表,后面跟着空白和一些可选的数字。现在我有这个:

>>> import re
>>> m = re.match('(?P<words>(\S+\s+)+)(?P<num>\d+)?\r\n', 'Foo Bar  12345\r\n')
>>> m.groupdict()
{'num': '12345', 'words': 'Foo Bar  '}

我希望单词组不包括最后的空白,但我搞不定这个。我 可以 在结果上用 .strip() 来去掉空白,但那样就没那么有趣了 :)


这里有一些测试用的字符串和 想要的 结果:

'Foo & Bar 555\r\n' => {'num': '555', 'words': 'Foo & Bar'}

'Hello World\r\n' => {'num': None, 'words': 'Hello World'}

'Spam     99\r\n' => {'num': 99, 'words': 'Spam'}

'Number 1 666\r\n' => {'num': 666, 'words': 'Number 1'}

1 个回答

2

我对你使用的双捕获组有点困惑,还有你用的\w,但想匹配像&这样的非字母字符(也许你是想用\S,表示非空格的字符,而你却用了\w...?),不过,也许...:

>>> import re
>>> r = re.compile(r'(?P<words>\w+(?:\s+\S+)*?)\s*(?P<num>\d+)?\r\n')
>>> for s in ('Foo & Bar 555\r\n', 'Hello World\r\n', 'Spam     99\r\n',
...           'Number 1 666\r\n'):
...   print s, r.match(s).groupdict()
... 
Foo & Bar 555
{'num': '555', 'words': 'Foo & Bar'}
Hello World
{'num': None, 'words': 'Hello World'}
Spam     99
{'num': '99', 'words': 'Spam'}
Number 1 666
{'num': '666', 'words': 'Number 1'}
>>> 

撰写回答