Python在字符串的开头匹配'.\'

Jam*_*all 4 python regex string substring

我需要确定一些powershell路径字符串在哪里交叉到Python中.

如何检测Python中的路径是否以.\

这是一个例子:

import re

file_path = ".\reports\dsReports"

if re.match(r'.\\', file_path):
    print "Pass"
else:
    print "Fail"
Run Code Online (Sandbox Code Playgroud)

这个失败,在它列出的调试器中

  expression = .\\\\\\
   string = .\\reports\\\\dsReports
Run Code Online (Sandbox Code Playgroud)

如果我尝试使用替换如此:

import re

file_path = ".\reports\dsReports"
testThis = file_path.replace(r'\', '&jkl$ff88')

if re.match(r'.&jkl$ff88', file_path):
    print "Pass"
else:
    print "Fail"
Run Code Online (Sandbox Code Playgroud)

所述testThis可变结束这样的:

testThis = '.\\reports&jkl$ff88dsReports'
Run Code Online (Sandbox Code Playgroud)

相当苛刻.

wha*_*000 6

发生这种情况的原因是因为\r是一个转义序列.你需要通过加倍来逃避反斜杠,或者使用像这样的原始字符串文字:

file_path = r".\reports\dsReports"
Run Code Online (Sandbox Code Playgroud)

然后检查它是否以以下内容开头".\\":

if file_path.startswith('.\\'):
    do_whatever()
Run Code Online (Sandbox Code Playgroud)

  • @donkopotamus:原始字符串文字不能以单个反斜杠结尾; 反斜杠可以防止```被解释为文字的结尾. (3认同)
  • @JamieMarshall:我的正则表达式与[我的测试](https://ideone.com/PvuvWV)中应该匹配的内容相匹配.你的正则表达式匹配它不应该的东西,比如"potatos". (2认同)