我有一个字符串:
"foo hello world baz 33"
foo
和baz
之间的部分将是一些空格分隔的单词(一个或多个)。我想将这个字符串与一个 re 匹配,该 re 将对每个单词进行分组:
>>> re.match(r'foo (<some re here>) baz (\d+)', "foo hello world baz 33").groups()
('hello', 'world', '33')
re 应该是灵活的,这样它就可以在没有单词的情况下工作:
>>> re.match(r'(<some re here>)', "hello world").groups()
('hello', 'world')
我正在尝试使用 ([\w+\s])+
进行变体,但我无法捕获动态确定的组数。这可能吗?
最佳答案
re.match
在字符串的开头返回结果。请改用 re.search
。
.*?
返回两个单词/表达式之间的最短匹配(。表示任何内容,* 表示出现 0 次或多次,? 表示最短匹配)。
import re
my_str = "foo hello world baz 33"
my_pattern = r'foo\s(.*?)\sbaz'
p = re.search(my_pattern,my_str,re.I)
result = p.group(1).split()
print result
['hello', 'world']
编辑:
如果缺少 foo 或 baz,并且您需要返回整个字符串,请使用 if-else
:
if p is not None:
result = p.group(1).split()
else:
result = my_str
为什么 ?
在模式中:
假设单词 baz
出现多次:
my_str = "foo hello world baz 33 there is another baz"
使用 pattern = 'foo\s(.*)\sbaz'
将匹配(最长且贪婪):
'hello world baz 33 there is another'
然而,使用 pattern = 'foo\s(.*?)\sbaz'
将返回最短匹配:
'hello world'
关于python - 正则表达式 : matching and grouping a variable number of space separated words,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33416263/