[英]Last matching symbol in Regex
I couldn't find a more descriptive title, but here there is an example: 我找不到更具描述性的标题,但是这里有一个示例:
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
This regex finds the first parenthesis, and I would like to match the last parenthesis for always getting 'Menda'. 此正则表达式找到第一个括号,而我想匹配最后一个括号以始终获得“ Menda”。 I've made a workaround to this using extra functions, but I would like a cleaner and a more consistent way using the same regex. 我已经使用其他功能对此进行了变通,但是我希望使用相同的正则表达式更简洁,更一致。
Thanks a lot guys. 非常感谢。
re.search(r"\((?P<remixer>[^)]+) (Remix)\)", "Title (Blabla) (Menda Remix)")
使用[^()]+
而不是.+
来不匹配括号。
我可能会这样做:
m = re.search(r".*\((?P<remixer>.+) (Remix)\)", "Title (Blabla) (Menda Remix)")
Just add a $
to the end of the pattern and you're done :) 只需在模式末尾添加一个$
,就可以完成:)
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: I've also changed the .+
to [^)]+
so you won't match any )
in the process. PS:我也将.+
更改为[^)]+
因此在此过程中,您将不会匹配任何)
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.