简体   繁体   中英

Python regex error with tuple. Works with list. Bad escape (end of pattern)

I have a list inside a dictionary that holds regex expressions and the program runs as expected. However, when I turn the list into a tuple I get error bad escape (end of pattern) at position 0.

The below gives the error.

import re

phone_num = '660-349-6829'

dict20 = {"phone": (r'\d{3}[-\.\s]??\d{3}[-\.\s]??\d{4}|\(\d{3}\)\s*\d{3}[-\.\s]??\d{4}|\d{3}[-\.\s]??\d{4}')}

for k in dict20["phone"]:
    print(k)
    results = re.findall(k, phone_num)
    print(results)


self.string, len(self.string) - 1) from None
sre_constants.error: bad escape (end of pattern) at position 0

This works fine (note list instead of tuple).

import re

phone_num = '660-349-6829'

dict20 = {"phone": [r'\d{3}[-\.\s]??\d{3}[-\.\s]??\d{4}|\(\d{3}\)\s*\d{3}[-\.\s]??\d{4}|\d{3}[-\.\s]??\d{4}']}

for k in dict20["phone"]:
    print(k)
    results = re.findall(k, phone_num)
    print(results)

That's not a tuple - just parentheses. You have to add a comma before ')' to make it a tuple.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM