正则表达式:匹配两个斜杠之间的字符串如果该字符串包含转义斜杠
我正在尝试构建一个正则表达式,用来匹配两个斜杠之间的正则表达式。我的主要问题是,正则表达式本身可能会包含斜杠,而这些斜杠是用反斜杠转义的。我试图通过负向前瞻断言来过滤掉这些斜杠(也就是说,只有在当前位置没有反斜杠的情况下,才匹配结束的斜杠),但是现在我遇到的问题是,如果正则表达式本身实际上以一个被转义的反斜杠结尾,我就无法匹配。
测试程序:
#!/usr/bin/python
import re
teststrings=[
"""/hello world/""",
"""/string with foreslash here \/ and here\//""",
"""/this one ends with backlash\\\\/"""]
patt="""^\/(?P<pattern>.*)(?<!\\\\)\/$"""
for t in teststrings:
m=re.match(patt,t)
if m!=None:
print t,' => MATCH'
else:
print t," => NO MATCH"
输出:
/hello world/ => MATCH
/string with foreslash here \/ and here\// => MATCH
/this one ends with backlash\\/ => NO MATCH
我该如何修改这个断言,使其只在当前位置有一个反斜杠时匹配,而不是两个反斜杠?
或者有没有更好的方法来提取这个正则表达式?(注意,在我实际尝试解析的文件中,每行包含的不仅仅是正则表达式。我不能简单地搜索每行的第一个和最后一个斜杠,然后获取它们之间的内容。)
1 个回答
17
试试这个:
pattern = re.compile(r"^/(?:\\.|[^/\\])*/")
解释:
^ # Start of string
/ # Match /
(?: # Match either...
\\. # an escaped character
| # or
[^/\\] # any character except slash/backslash
)* # any number of times.
/ # Match /
对于你的“实际应用”(寻找第一个用斜杠分隔的字符串,忽略转义的斜杠),我会使用
pattern = re.compile(r"^(?:\\.|[^/\\])*/((?:\\.|[^/\\])*)/")
这样你就能得到以下内容:
>>> pattern.match("foo /bar/ baz").group(1)
'bar'
>>> pattern.match("foo /bar\/bam/ baz").group(1)
'bar\\/bam'
>>> pattern.match("foo /bar/bam/ baz").group(1)
'bar'
>>> pattern.match("foo\/oof /bar\/bam/ baz").group(1)
'bar\\/bam'