Word boundary with words starting or ending with special characters gives unexpected results
See what a word boundary matches:
A word boundary can occur in one of three positions:
- Before the first character in the string, if the first character is a word character.
- After the last character in the string, if the last character is a word character.
- Between two characters in the string, where one is a word character and the other is not a word character.
In your pattern }\b
only matches if there is a word char after }
(a letter, digit or _
).
When you use (\W|$)
you require a non-word or end of string explicitly.
I always recommend unambiguous word boundaries based on negative lookarounds in these cases:
re.search(r'(?<!\w){}(?!\w)'.format(re.escape('Sortes\index[persons]{Sortes}')), 'test Sortes\index[persons]{Sortes} test')
Here, (?<!\w)
negative lookbehind will fail the match if there is a word char immediately to the left of the current location, and (?!\w)
negative lookahead will fail the match if there is a word char immediately to the right of the current location.
Actually, it is easy to customize these lookaround patterns further (say, to only fail the match if there are letters around the pattern, use [^\W\d_]
instead of \w
, or if you only allow matches around whitespaces, use (?<!\S)
/ (?!\S)
lookaround boundaries).