regex OR/ALTERNATIVE help
Need a little help with a regex
I'm trying to match a string that falls at the begging or end of a larger string, or follows or is followed by whitepace. Or any combination of the two.
(Basically I want to find a particular string, but only match it if it is not part of another word or phrase. IE if the string I was searching for was "are" I wouldn't want to match "are" in the word "area", hence either beginning or end of searched string, or follows or is followed by whitespace.)
Here is what I have now:
re.compile('^(%(string)s)$|\s(%(string)s)$|^(%(string)s)\s|\s(%(string)s)\s' % {'string': 开发者_如何学Pythonmy_string})
Is there a less verbose way of writing this using two |'s . One at the beging for start or whitespace, and one at the end for end or whitespace?
Write now I am writing out every permutation of beginning options * end option and figure its less efficient.
Wrap your search term with \b
s:
\bstring\b
\b
matches a word boundary, and importantly is "zero-width" (consumes no characters)
精彩评论