[英]Regex - Python: Capture three (3) words after a specific word
大家好,我有以下代码:
str1 = "Hello, I would like to meet you at the train station of Berlin after 6 o' clock"
match = re.compile(r' at \w+ \w+ \w+')
match.findall(str1)
有没有比“ \\ w + \\ w + \\ w”更好的方法,例如捕获特定数量的单词?
是。 要为匹配指定一个特定的计数,请使用大括号。 例如,:
match = re.compile(r'at ((\w+ ){3})')
这使:
>>> print match.findall(str1)
[('the train station ', 'station ')]
通常,仅捕获word之后的n
word
,您的正则表达式为:
'word\s+((?:\w+(?:\s+|$)){n})'
其中?:
表示“非捕获”组, \\s
表示空白, |
表示“或”,而$
表示“字符串结尾”。 因此:
>>> print re.compile(r'at\s+((?:\w+(?:\s+|$)){3})').findall(str1)
['the train station ']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.