Python: Using same named capture group multiple times in one regex

Viewed 647

Is it anyway possible to repeat a named capture group multiple times in one regex using Python?

Below is the regex (which is incorrect as there are duplicate named groups in the same regex)

regex = r'''Use ((?P<phn_num>(?<=(Phone: ))\d{10})?(?P<lndln_num>(?<=(landline: ))\d{10})?) 
or you can also use
((?P<phn_num>(?<=(Phone: ))\d{10})?(?P<lndln_num>(?<=(Landline: ))\d{10})?)'''

The input string will be either of the below:

 1. Use Phone: 1234567890 or you can also use Landline: 0012345678
 2. Use Landline: 0012345678 or you can also use Phone: 1234567890

The objective is to make one regex capture both phn_num and lndln_num as named capture groups if any of the above string is given as input.

1 Answers

The pattern is not anchored, so you can use an alternation | instead using both named capture groups to match both variations.

Using a case insensitive match:

\bUse (?:Phone: (?P<phn_num>\d{10})|landline: (?P<lndln_num>\d{10}))
  • \bUse Match Use preceded by a word boundary and match a space
  • (?: Non capture group for the alternation
    • Phone: (?P<phn_num>\d{10}) Match phone: and 10 digits
    • | Or
    • landline: (?P<lndln_num>\d{10}) Match landline: and 10 digits
  • )

Regex demo

Related