Regular expression to search for plural or singular of specific python

时间:2016-07-11 20:04:54

标签: python regex

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)

1 个答案:

答案 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.