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)
相当苛刻.
发生这种情况的原因是因为\r是一个转义序列.你需要通过加倍来逃避反斜杠,或者使用像这样的原始字符串文字:
file_path = r".\reports\dsReports"
Run Code Online (Sandbox Code Playgroud)
然后检查它是否以以下内容开头".\\":
if file_path.startswith('.\\'):
do_whatever()
Run Code Online (Sandbox Code Playgroud)