gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 22:05:58 25 4
gpt4 key购买 nike

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

测试程序:

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com