我正在尝试构建一个正则表达式,它匹配两个正斜杠之间的正则表达式。我的主要问题是正则表达式本身可以包含正斜杠,通过反斜杠进行转义。我试图用一个负的回溯断言过滤掉它们(只有在当前位置没有反斜杠的情况下才匹配结束斜杠),然而,现在我遇到了一个问题,如果正则表达式本身实际上以一个转义的反斜杠结束,我就得不到匹配。
测试程序:
#!/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
如果在当前位置只有一个反冲,而不是两个反冲,我如何修改断言以仅命中?
或者是否有更好的方法来提取正则表达式?(请注意,在实际的文件中,我尝试解析的行不仅仅包含regex。我不能简单地搜索每行的第一个和最后一个斜杠,然后得到中间的所有内容。)
发布于 2011-12-12 19:55:57
试试这个:
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'
https://stackoverflow.com/questions/8473853
复制相似问题