繁体   English   中英

正则表达式与 Python 从行尾匹配

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM