python - 正则表达式 : Match string between two slashes if the string itself contains escaped slashes

标签 python regex

我正在尝试构建一个正则表达式来匹配两个正斜杠之间的正则表达式。我的主要问题是正则表达式本身可以包含正斜杠,由反斜杠转义。我尝试用否定的后视断言过滤掉它们(如果当前位置没有反冲,则只匹配结束斜杠),但是,现在我遇到了一个问题,如果正则表达式本身,我没有得到匹配实际上以转义的反斜杠结束。

测试程序:

#!/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

如果当前位置有一个反弹,而不是两个,我如何修改断言以仅命中?

或者是否有更好的方法来提取正则表达式? (请注意,在实际文件中,我尝试解析的行不仅仅包含正则表达式。我不能简单地搜索每行的第一个和最后一个斜杠并获取其间的所有内容。)

最佳答案

试试这个:

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'

关于python - 正则表达式 : Match string between two slashes if the string itself contains escaped slashes,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8473853/

相关文章:

javascript - 正则表达式:两个或多个连续的字符或字符序列

python - 匹配 PEP440 兼容版本字符串的正则表达式

python - 看门狗无法检测到 ubuntu 中的删除事件

python - Django JSONField过滤查询集,其中过滤值是带注释的总和值

python - 在 Python 中仅初始化一次字段

python - 如何在 osx 上安装 pycairo?

javascript - 如何通过正则表达式从url获取优酷视频id?

Javascript:扫描关键字列表时的 Regex 与 IndexOf

python - Celery 使用来自 python 的 -Ofair 运行 worker

php - 用于解析YouTube嵌入式代码的正则表达式