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

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.



Solution 1:[1]

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.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Wiktor Stribiżew