我需要确定一些PowerShell路径字符串跨越Python的位置。Python匹配'。'在字符串开头
如何检测Python中的路径是否以.\
开头?
下面是一个例子:
import re
file_path = ".\reports\dsReports"
if re.match(r'.\\', file_path):
print "Pass"
else:
print "Fail"
失败,在调试器中它列出
expression = .\\\\\\
string = .\\reports\\\\dsReports
如果我尝试使用像这样替换:
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"
的testThis
变量结束像这样:
testThis = '.\\reports&jkl$ff88dsReports'
相当严重。
为什么不能用“如果'。''== file_path [0:2]“或”if'。''in file_path“? – Mike
通常,对Windows路径使用原始字符串,而不仅仅是正则表达式模式。在这种情况下,路径中的\ r被转换为回车符,但还有很多其他组合会出现类似的问题(例如'\ a','\ b','\ f','\ n ''\ t','\ v','\ x'和Python 3'str'和Python 2'unicode'文字,'\ u','\ U')。 – ShadowRanger