gpt4 book ai didi

python - 正则表达式-Python : Capture three (3) words after a specific word

转载 作者:太空宇宙 更新时间:2023-11-04 10:12:28 25 4
gpt4 key购买 nike

大家好,我有以下代码:

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\s+((?:\w+(?:\s+|$)){n})'

?: 表示“非捕获”组,\s 表示空白,| 表示“或”,$ 表示“字符串结尾”。因此:

>>> print re.compile(r'at\s+((?:\w+(?:\s+|$)){3})').findall(str1)
['the train station ']

关于python - 正则表达式-Python : Capture three (3) words after a specific word,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37497634/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com