Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

self.phoneRegex = re.compile(r'(\+\d) (\(\d\d\d\)) (\d\d\d)(\d\d\d\d)')

Here is the code causing the issues:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

for cell in self.cells:
    if '+1' in cell.text:
        print(self.pmo.groups()) #Works fine
        print("{} {} {}-{}".format(self.pmo.groups())) #Errors out.
        print("{} {} {}-{}".format(self.pmo.group(1), self.pmo.group(2),self.pmo.group(3), self.pmo.group(4))) #Also errors out.
        if isinstance(self.cursor(row=self.data['lst_row'], column=self.telCol).value, type(None)):
            self.cursor(row=self.data['lst_row'], column=self.telCol).value = "{} {};".format("{} {} {}-{}".format(self.pmo.group(2), self.pmo.group(2),self.pmo.group(3), self.pmo.group(4)))

Full Traceback:

Traceback (most recent call last):
  File "F:\Documents\Programs\Python\E45 Contact Info Puller\main.py", line 289, in run
    print("{} {} {}-{}".format(self.pmo.groups()))
IndexError: Replacement index 1 out of range for positional args tuple

>Solution :

You have this string.format line:

print("{} {} {}-{}".format(self.pmo.groups())) 

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().

print("{} {} {}-{}".format(*self.pmo.groups())) 
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading