tags:

views:

43

answers:

4

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'. 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.

+3  A: 
re.search(r"\((?P<remixer>[^)]+) (Remix)\)", "Title (Blabla) (Menda Remix)")
Ignacio Vazquez-Abrams
+1  A: 

Use [^()]+ instead of .+ to not to match the parenthesis.

KennyTM
+1  A: 

I would probably do this:

m = re.search(r".*\((?P<remixer>.+) (Remix)\)", "Title (Blabla) (Menda Remix)")
sharth
+1  A: 

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.

WoLpH
the reason it matches has nothing whatsoever to do with `$` and all with the change to character class
SilentGhost
If there would be more matches than it would still only get the last match so it's still a useful addition
WoLpH