Python 要匹配后续单词的正则表达式
在这个正则表达式中:Python 要匹配后续单词的正则表达式,python,regex,Python,Regex,在这个正则表达式中:test3\w+我试图匹配'test1,test2,test3 match1 match2 tester'中单词test3后的两个单词 以下是我的尝试: import re words = 'test1, test2, test3 match1 match2 tester' # match the words match1 match2 # note these two words can be anything but are preceded by test3 pr
test3\w+
我试图匹配'test1,test2,test3 match1 match2 tester'中单词test3
后的两个单词
以下是我的尝试:
import re
words = 'test1, test2, test3 match1 match2 tester'
# match the words match1 match2
# note these two words can be anything but are preceded by test3
print(re.compile(r'test3\w+').search(words).group())
如何在test3
匹配后捕获单词
应返回单词match1 match2
。使用以下正则表达式:
test3\s([^\s]+)\s([^\s]+)
这将为您提供两个组,一个为match1
,另一个为match2
请参见您可以使用类似的正则表达式
test3\s(\w+)\s(\w+)\s
说明:
>>> words = 'test1, test2, test3 match1 match2 tester'
>>> match = re.search(r'test3\s(\w+)\s(\w+)\s', words)
>>> match.group(1) # returns what is matched btw first pair of paranthesis.
match1
>>> match.group(2) # returns what is matched btw second pair of paranthesis.
match2
- \s-匹配任何空白字符
- \w-匹配任何字母数字字符和下划线
- +-匹配一个或多个事件。(因此,\w+匹配一个或多个字母数字字符)
演示:
>>> words = 'test1, test2, test3 match1 match2 tester'
>>> match = re.search(r'test3\s(\w+)\s(\w+)\s', words)
>>> match.group(1) # returns what is matched btw first pair of paranthesis.
match1
>>> match.group(2) # returns what is matched btw second pair of paranthesis.
match2
为什么不需要测试仪?尝试r'test3((?:\s+\w+{0,2})
并访问.group(1).strip()
。在访问组之前检查匹配项,这样会更安全。