I want to use a regular expression to search for dog or dogs in a certain sentence. Here is what I have but its not working. I need it to search for the specific word, not just a plural or singular of all words.
x = re.findall('(?<=\|)dog[s]?(?=\|)', txt)
答案 0 :(得分:3)
A quantifier is applied to the atom on the left. If it is a group, it will be applied to a group. If it is a literal symbol, it will be applied to this symbol.
So, s?
matches 1 or 0 s
.
Use
x = re.findall(r'\bdogs?\b', txt)
where \b
are word boundaries, and s
is optional.
Note: using raw string literals to define regex patterns are preferred in order to avoid issues related to escaping special regex metacharacters.