Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
325 views
in Technique[技术] by (71.8m points)

python - Match a whole word in a string using dynamic regex

I am looking to see whether a word occurs in a sentence using regex. Words are separated by spaces, but may have punctuation on either side. If the word is in the middle of the string, the following match works (it prevents part-words from matching, allows punctuation on either side of the word).

match_middle_words = " [^a-zA-Zd ]{0,}" + word + "[^a-zA-Zd ]{0,} "

This won't however match the first or last word, since there is no trailing/leading space. So, for these cases, I have also been using:

match_starting_word = "^[^a-zA-Zd]{0,}" + word + "[^a-zA-Zd ]{0,} "
match_end_word = " [^a-zA-Zd ]{0,}" + word + "[^a-zA-Zd]{0,}$"

and then combining with

 match_string = match_middle_words  + "|" + match_starting_word  +"|" + match_end_word 

Is there a simple way to avoid the need of three match terms. Specifically, is there a way of specifying 'ether a space or the start of file (i.e. "^") and similar, 'either a space or the end of the file (i.e. "$")?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Why not use a word boundary?

match_string = r'' + word + r''
match_string = r'{}'.format(word)
match_string = rf'{word}'          # Python 3.7+ required

If you have a list of words (say, in a words variable) to be matched as a whole word, use

match_string = r'(?:{})'.format('|'.join(words))
match_string = rf'(?:{"|".join(words)})'         # Python 3.7+ required

In this case, you will make sure the word is only captured when it is surrounded by non-word characters. Also note that matches at the string start and end. So, no use adding 3 alternatives.

Sample code:

import re
strn = "word hereword word, there word"
search = "word"
print re.findall(r"" + search + r"", strn)

And we found our 3 matches:

['word', 'word', 'word']

NOTE ON "WORD" BOUNDARIES

When the "words" are in fact chunks of any chars you should re.escape them before passing to the regex pattern:

match_string = r'{}'.format(re.escape(word)) # a single escaped "word" string passed
match_string = r'(?:{})'.format("|".join(map(re.escape, words))) # words list is escaped
match_string = rf'(?:{"|".join(map(re.escape, words))})' # Same as above for Python 3.7+

If the words to be matched as whole words may start/end with special characters, won't work, use unambiguous word boundaries:

match_string = r'(?<!w){}(?!w)'.format(re.escape(word))
match_string = r'(?<!w)(?:{})(?!w)'.format("|".join(map(re.escape, words))) 

If the word boundaries are whitespace chars or start/end of string, use whitespace boundaries, (?<!S)...(?!S):

match_string = r'(?<!S){}(?!S)'.format(word)
match_string = r'(?<!S)(?:{})(?!S)'.format("|".join(map(re.escape, words))) 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...