繁体   English   中英

正则表达式以匹配后续单词

[英]Regex to match subsequent words

在这个正则表达式中: 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应该被返回。

您可以使用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

使用以下正则表达式:

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

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

参见https://regex101.com/r/NvPExD/1

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM