Search code examples
pythonregexcapturing-group

regex get rid of capturing groups


I have the following regex: (?i)p\w+@t(-)?\w+(-\w+)?(\.\w+)?\.at which is matching data like

papFoo@t-bar.at
PapBar@tfoo.ring.at

How can I rewrite this regex to use non-captchuring groups?

  • [?i]p\w+@t[-]?\w+[-\w+]?[\.\w+]?\.at will no longer match any results
  • (?:?i)p\w+@t(?:-)?\w+(?:-\w+)?(?:\.\w+)?\.at same here

I.e. (?i)p should be writable as ?ip I think but on https://regex101.com I only get errors when trying to use (?:?i)p\w+@t(?:-)?\w+(?:-\w+)?(?:\.\w+)?\.at with non-captchuring groups.

In the end python3 should evaluate the regex.


Solution

  • The first "group", (?i), is not a capturing group, it's a flag set, turning on case-insensitivity for the expression. The non-capturing version should be:

    (?i)p\w+@t-?\w+(?:-\w+)?(?:\.\w+)?\.at
    

    Which matches correctly.