gpt4 book ai didi

python - 我需要帮助制定特定的正则表达式

转载 作者:行者123 更新时间:2023-11-30 22:29:27 26 4
gpt4 key购买 nike

我不认为自己是正则表达式的新手,但我似乎发现了一个困扰我的问题(也是周五晚上,所以大脑没有处于最佳性能)。

我正在尝试用其他值替换字符串内的占位符。我很难获得按照我想要的方式运行的语法。我的占位符采用以下格式:{swap}

我希望它捕获并替换这些:

    {swap}    # NewValue
x{swap}x # xNewValuex
{swap}x # NewValuex
x{swap} # xNewValue

但我希望它不匹配这些:

    {{swap}}    # NOT {NewValue}
x{{swap}}x # NOT x{NewValue}x
{{swap}}x # NOT {NewValue}x
x{{swap}} # NOT x{NewValue}

在上述所有内容中,x 可以是任意长度的任何字符串,无论是否为“单词”。

我正在尝试使用 python3 的 re.sub() 来做到这一点,但每当我满足一个标准子集时,我就会在这个过程中失去另一个。我开始认为这可能无法通过单个命令来完成。

干杯!

最佳答案

如果您能够使用较新的 regex模块,您可以使用 (*SKIP)(*FAIL):

{{.*?}}(*SKIP)(*FAIL)|{.*?}

参见a demo on regex101.com

<小时/>分割来看,这表示:

{{.*?}}(*SKIP)(*FAIL) # match any {{...}} and "throw them away"
| # or ...
{.*?} # match your desired pattern

<小时/>在 Python 中,这将是:

import regex as re

rx = re.compile(r'{{.*?}}(*SKIP)(*FAIL)|{.*?}')

string = """
{swap}
x{swap}x
{swap}x
x{swap}

{{swap}}
x{{swap}}x
{{swap}}x
x{{swap}}"""

string = rx.sub('NewValue', string)
print(string)

这会产生:

NewValue    
xNewValuex
NewValuex
xNewValue

{{swap}}
x{{swap}}x
{{swap}}x
x{{swap}}

<小时/>为了完整起见,您还可以使用 Python 自己的 re 模块来实现此目的,但在这里,您需要稍微调整一下模式以及替换函数:

import re

rx = re.compile(r'{{.*?}}|({.*?})')

string = """
{swap}
x{swap}x
{swap}x
x{swap}

{{swap}}
x{{swap}}x
{{swap}}x
x{{swap}}"""


def repl(match):
if match.group(1) is not None:
return "NewValue"
else:
return match.group(0)

string = rx.sub(repl, string)
print(string)

关于python - 我需要帮助制定特定的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46370042/

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