Skip to content
Advertisement

Python Regex groups causing index errors

So, my interpereter is complaining about IndexError: Replacement index 1 out of range for positional args tuple when calling re.group(#) or re.groups() under specific circumstances. It is meant to return a phone number, such as +1 (555) 555-5555

Here is the regex used, as it is declared elsewhere:

JavaScript

Here is the code causing the issues:

JavaScript

Full Traceback:

JavaScript

Advertisement

Answer

You have this string.format line:

JavaScript

re match groups are tuples, so here, you have 4 format substitutions, but you’re trying to pass a single tuple (that contains 4 matches per your regex) instead of 4 separate argument for formatting.

You need to unpack (or splat) the tuple for the string formatting – notice the * added before self.pmo.groups().

JavaScript
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement