python – How to exactly match a word with one regexp?
Using Python 3.9.13.
How can I match an exact word without preceding or trailing character with a simple one regexp expression?
There are answers using the boundary word \b. However, according to the Python doc, it can match non word characters.
\b: Matches the empty string, but only at the beginning or end of a word. A word is defined as a sequence of word characters. Note that formally,\bis defined as the boundary between a\wand a\Wcharacter (or vice versa), or between\wand the beginning/end of the string.
For instance, I want to get a match only with the word cool, but no match with #cool or cool..
re.findall(
pattern=r'\bcool\b',
string=" #cool",
flags=re.IGNORECASE|re.ASCII
)
---
['cool']
Alternative can be listing multiple patterns but it is not clean.
re.findall(
pattern=r'\Acool\Z|\s+cool\s+|^cool\s+|\s+cool\Z',
string=" #cool",
flags=re.IGNORECASE|re.ASCII
)
---
Please advise if there is better and simple one regexp pattern to achieve this.
As answered by The fourth bird
re.findall(
pattern=r'(?<!\S)cool(?!\S)',
string=" #cool cool& cool cool\n (cool)",
flags=re.IGNORECASE|re.ASCII
)
---
['cool', 'cool']
or
re.findall(
pattern=r'(?<=\s|^)cool(?=\s|$)',
string=" #cool cool& cool cool\n (cool)",
flags=re.IGNORECASE|re.ASCII
)
---
['cool', 'cool']
Read more here: Source link
