簡體   English   中英

正則表達式-Python:在特定單詞之后捕獲三(3)個單詞

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM