Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular expression to search for plural or singular of specific python

Tags:

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)
like image 764
Harp Angell Avatar asked Jul 11 '16 20:07

Harp Angell


1 Answers

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.

like image 194
Wiktor Stribiżew Avatar answered Nov 04 '22 11:11

Wiktor Stribiżew