[英]Regex match with Python re from end of line
我匹配最后一個單詞“City”或“City City”。
適用於 regex101.com ( https://regex101.com/r/7F6Jao/1 ) 但不在 ZA7F5F35426B927411FC9231B56382.
folder = i.find ( 'folder' ).text
# Top > Continent > Country > City
country = re.match ( r'\s+\S*$', folder )
print ( folder )
Output 我得到“無”。
您應該在此處使用re.search
,因為您不希望將正則表達式模式錨定到輸入的開頭(這是re.match
的默認行為):
text = "Top > Continent > Country > City"
p = re.compile("\\b\\S*$")
matches = p.search(text)
if matches:
print("Found a match: " + matches.group(0))
else:
print("no match")
這打印:
Found a match: City
編輯:
感謝您為我指明正確的方向。
另外對於場景(對於帶有 2 個單詞的城市名稱):
# Top > Continent > Country > City City
p = re.compile("[^ ]+\\s+[^ ]+$")
Output:
City City
> City
似乎不能排除最后一個'>'。
也許從左邊匹配捕獲 3 '>' 后的所有內容加上一個空格?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.