Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/318.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 要匹配后续单词的正则表达式_Python_Regex - Fatal编程技术网

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()
。在访问组之前检查匹配项,这样会更安全。