Python regex *_*_policy pattern to match *_*_policies

Viewed 26
pattern = "abc_xyz_policy"
search_string = """
bla bla
abc_xyz_policies
bla bla
"""

I can make

pattern = pattern[:-1] + "ies"

and

search = re.search(pattern, search_string)

to make it work.

However, I was wondering if there is a better way to solve this?

Thanks.

1 Answers

You need to use

  • a non-capturing group at the end to match either y or ies
  • use wor boundary or word boundaries to make sure you match the whole word.

You need

search = re.search(r'\babc_xyz_polic(?:ies|y)\b', search_string)

where

  • \b - a word boundary
  • abc_xyz_polic - a literal text
  • (?:ies|y) - ies or y
  • \b - a word boundary.
Related