Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/19.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正则表达式应该匹配时,python正则表达式不匹配_Python_Regex - Fatal编程技术网

当正则表达式工具指示python正则表达式应该匹配时,python正则表达式不匹配

当正则表达式工具指示python正则表达式应该匹配时,python正则表达式不匹配,python,regex,Python,Regex,我在脚本中有一个if语句,以查看通过argparse给出的目录是否是UNC路径。但不会以尾部斜杠结束 import re #dest is set by argparse. but for this purpose i'll set it manually. #originally i was escaping each \ in dest. But I found that argparse left them alone. dest = '\\server-name\folder\subf

我在脚本中有一个if语句,以查看通过argparse给出的目录是否是UNC路径。但不会以尾部斜杠结束

import re

#dest is set by argparse. but for this purpose i'll set it manually.
#originally i was escaping each \ in dest. But I found that argparse left them alone.
dest = '\\server-name\folder\subfolder'

if re.match ('^\\+[\w\W]+', dest ) and not re.match( '^\\+[\w\W]+\\$', dest):
    dest = dest + '\\'
我一直在ipython玩这个。第一条语句不匹配。我在Komodo IDE中使用了RxToolkit,它显示了匹配的正则表达式。我试过这个网络工具:它也匹配。有什么想法吗?

字符串
“\\”
表示一个反斜杠
\

>>> print('\\')
\
您需要转义
\
,或者应该使用原始字符串文字来表示两个反斜杠

>>> print('\\\\')
\\
>>> print(r'\\')
\\

顺便说一句,检查字符串开头是否匹配;您可以省略要将其传递给re的前导
^

^\+[\w\W]+
因为
\\
意味着
\
。您需要做的是通过使用
r
,来绘制正则表达式字符串:

if re.match(r'^\\+[\w\W]+', dest ) and not re.match(r'^\\+[\w\W]+\\$', dest):
            ^                                       ^