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?
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).
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)
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With