Home > Net >  Python Regex groups causing index errors
Python Regex groups causing index errors

Time:06-22

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:

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

CodePudding user response:

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())) 
  • Related