'Python regular expressions match end of word

For example, how to match the second _ab in the sentence _ab_ab is a test? I tried \> to match end of word, but not work for Python 2.7. Note: I am matching not end of a string, but end of a single word.

There are implicit answers in other posts. But I believe a simple and direct answer to such question should be advocated. So I ask it after trying the following posts without direct & concise solutions found.

  1. Python Regex to find whitespace, end of string, and/or word boundary

  2. Does Python re module support word boundaries (\b)?



Solution 1:[1]

You may use word boundary \b at the last. Note that adding \b before _ab won't work because there is a b (word char) exists before underscore. \b matches between a word character and a non-word character(vice-versa).

r'_ab\b'

Solution 2:[2]

use r'\>' rather than just '\>'.

I find this solution after reading this post: https://stackoverflow.com/a/3995242/2728388

When using the re module in Python, remember Python’s raw string notation, add a r prefix to escape backslash in your regular expressions.

Any other solutions, such as using word boundary \b?

Solution 3:[3]

import re
string='''ab_ab _ab_ab ab__ab abab_ ab_ababab_ '''
patt=re.compile(r'_ab\b')
#this will search _ab from the back of the string
allmatches=patt.findall(patt,string)
print(allmatches)

this will match all _ab form the back of the string

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Community
Solution 3 Shreyansh Gupta