简体   繁体   English

Python正则表达式错误与元组。 使用列表。 错误的转义(模式结束)

[英]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. 但是,当我将列表转换为元组时,在位置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. 您必须在')'之前添加逗号以使其成为元组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 错误:使用正则表达式在 Python 脚本中错误转义 - Error: bad escape in Python script with regex 错误:尝试替换为backslah时,位置0处的错误转义(模式结束) - error: bad escape (end of pattern) at position 0 while trying to replace to backslah Python字符串神奇地转换为元组。 为什么? - Python string converts magically to tuple. Why? Python 类型错误:列表索引必须是整数或切片,而不是元组。 凯撒 Cypher 解码器 - Python TypeError: list indices must be integers or slices, not tuple. Caesar Cypher Decoder 如何修复错误的转义正则表达式错误(python re) - How to fix bad escape regex error (python re) 有没有办法在 Python 中创建一个由列表给出的长度为“n”的元组。? - Is there a way to create a tuple in Python with a lenght 'n' given by a list.? 如何从txt文件中获取数据并将其输入到元组。 蟒蛇 - How to take data from a txt file and input it into a tuple. Python 关于 Python 空列表的错误。 未绑定本地错误 - Error regarding Python empty list. UnboundLocalError 类型错误:必须是 pygame.Surface,而不是元组。 Python/Pygame 菜鸟 - TypeError: must be pygame.Surface, not tuple. Python/Pygame noobie 模式意外结束:Python 正则表达式 - Unexpected end of Pattern : Python Regex
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM