Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find last match with python regular expression

Tags:

python

regex

I want to match the last occurrence of a simple pattern in a string, e.g.

list = re.findall(r"\w+ AAAA \w+", "foo bar AAAA foo2 AAAA bar2") print "last match: ", list[len(list)-1] 

However, if the string is very long, a huge list of matches is generated. Is there a more direct way to match the second occurrence of " AAAA ", or should I use this workaround?

like image 476
SDD Avatar asked May 10 '10 11:05

SDD


People also ask

How do you match in regex?

To match a character having special meaning in regex, you need to use a escape sequence prefix with a backslash ( \ ). E.g., \. matches "." ; regex \+ matches "+" ; and regex \( matches "(" . You also need to use regex \\ to match "\" (back-slash).

How do you check a string pattern in Python?

match("[a-z]+", "abcdef") ✅ will give a match. But! re. match("[a-z]+", "abcdef 12345") ✅ will also give a match because there is a part in string which matches (maybe you don't want that when you're checking if the entire string is valid or not)

How do you print a matching object in Python?

Note that re. match(pattern, string, flags=0) only returns matches at the beginning of the string. If you want to locate a match anywhere in the string, use re.search(pattern, string, flags=0) instead (https://docs.python.org/3/library/re.html). This will scan the string and return the first match object.


1 Answers

you could use $ that denotes end of the line character:

>>> s = """foo bar AAAA foo2 AAAA bar2""" >>> re.findall(r"\w+ AAAA \w+$", s) ['foo2 AAAA bar2'] 

Also, note that list is a bad name for your variable, as it shadows built-in type. To access the last element of a list you could just use [-1] index:

>>> lst = [2, 3, 4] >>> lst[-1] 4 
like image 179
SilentGhost Avatar answered Oct 02 '22 12:10

SilentGhost