正则表达式匹配后续单词

时间:2018-03-30 08:53:28

标签: python regex

在此正则表达式中:test3\w+我试图在test3

中的单词'test1, test2, test3 match1 match2 tester'之后匹配以下两个单词

这是我的尝试:

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

2 个答案:

答案 0 :(得分:1)

您可以使用regex之类的

test3\s(\w+)\s(\w+)\s

<强>解释

  • \ 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

答案 1 :(得分:0)

使用此正则表达式:

test3\s([^\s]+)\s([^\s]+)

这将为您提供两个组,一组match1,一组match2

请参阅https://regex101.com/r/NvPExD/1

相关问题