Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/286.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Python RE中使用反斜杠时出错_Python_Re - Fatal编程技术网

在Python RE中使用反斜杠时出错

在Python RE中使用反斜杠时出错,python,re,Python,Re,我的输出为否。我已尝试使用\来转义反斜杠,它是原始字符串。我不确定为什么我的模式不匹配。请帮忙。谢谢您的正则表达式是正确的。您缺少的是测试字符串中的转义字符(再加一个反斜杠) 以下代码为您提供了if条件的答案“是” test_string = "334-33\4455" match_string = r"^[0-9]{3}-{1}[0-9]{2}[\\]{1}[0-9]{4}" if re.match(match_string, test_string):

我的输出为否。我已尝试使用\来转义反斜杠,它是原始字符串。我不确定为什么我的模式不匹配。请帮忙。谢谢

您的正则表达式是正确的。您缺少的是测试字符串中的转义字符(再加一个反斜杠)

以下代码为您提供了if条件的答案“是”

test_string = "334-33\4455"
match_string = r"^[0-9]{3}-{1}[0-9]{2}[\\]{1}[0-9]{4}"
if re.match(match_string, test_string):
    print("Yes")
else:
    print("No")

test\u字符串
包含转义序列
\4
,而不是斜杠。您需要将其设置为原始字符串或使用
\\4
{1}
始终是多余的。也不需要将
\\
放入
[]
import re
test_string = "334-33\\4455" # Have added one more backslash
match_string = r"^[0-9]{3}-{1}[0-9]{2}[\\]{1}[0-9]{4}"
if re.match(match_string, test_string):
  print("Yes")
else:
  print("No")