[英]Last matching symbol in Regex
我找不到更具描述性的標題,但是這里有一個示例:
import re
m = re.search(r"\((?P<remixer>.+) (Remix)\)", "Title (Menda Remix)")
m.group("remixer") # returns 'Menda' OK
m = re.search(r"\((?P<remixer>.+) (Remix)\)", "Title (Blabla) (Menda Remix)")
m.group("remixer") # returns 'Blabla) (Menda' FAIL
此正則表達式找到第一個括號,而我想匹配最后一個括號以始終獲得“ Menda”。 我已經使用其他功能對此進行了變通,但是我希望使用相同的正則表達式更簡潔,更一致。
非常感謝。
re.search(r"\((?P<remixer>[^)]+) (Remix)\)", "Title (Blabla) (Menda Remix)")
使用[^()]+
而不是.+
來不匹配括號。
我可能會這樣做:
m = re.search(r".*\((?P<remixer>.+) (Remix)\)", "Title (Blabla) (Menda Remix)")
只需在模式末尾添加一個$
,就可以完成:)
import re
m = re.search(r"\((?P<remixer>[^)]+) (Remix)\)$", "Title (Menda Remix)")
print m.group("remixer") # returns 'Menda' OK
m = re.search(r"\((?P<remixer>[^)]+) (Remix)\)$", "Title (Blabla) (Menda Remix)")
print m.group("remixer") # returns 'Blabla) (Menda' FAIL
PS:我也將.+
更改為[^)]+
因此在此過程中,您將不會匹配任何)
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.