[英]Python Regular Expression to find the last occurrence of whitespace in a certain pattern
我在Python中使用正則表達式。 我想在特定模式中最后一次出現空格之前找到字符串。 例如,在下面的文字中,我想找到“街道”。 “星期一,[LOC Te Rapa Tika Street]的一名工人”。
任何人都可以幫我找到使用正則表達式的字符串嗎?
謝謝
在空格上拆分字符串並獲取第二個最后一個元素:
>>> strs = "On Monday , a worker at a [LOC Te Rapa Tika Street ]"
>>> strs.split()[-2]
'Street'
re.split
\\s+
re.split
by \\s+
並獲取返回列表中的第二個最后一個標記(例如,使用索引-2
)。
>>> import re
>>> match = re.search('\[\s?LOC.+\s(\w+)\s?\]', "[LOC Te Rapa Tika Street ]")
>>> match.group(1)
'Street'
無論支架上的間距如何,這都應該有效。
編輯:閱讀您的評論后,這將更好
>>> import re
>>> sentence = "A man strolling through the [LOC Pullman Hotel ] in [LOC Waterloo Quadrant ] on Sunday with the bag across his shoulder"
>>> match = re.findall('\[\s?LOC[^\]]+\s(\w+)\s?\]', sentence)
>>> match
['Hotel', 'Quadrant']
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.