gpt4 book ai didi

python - 如何使用 Regex Python 从序列中查找逻辑 'or' 运算符 (||)

转载 作者:太空宇宙 更新时间:2023-11-03 14:43:27 25 4
gpt4 key购买 nike

我想从我的序列中查找并替换逻辑“或”运算符 ( || )。我该怎么做?

以下是代码,我正在尝试

import re 
sequence = "if(ab||2) + H) then a*10"
expr = re.sub(r"||","_or_",sequence)
print (expr)

预期答案应该是

if(ab_or_2) + H) then a*10

最佳答案

此处需要使用转义序列\”,因为“|”是一个特殊字符。

Python docs :

'|'

A|B, where A and B can be arbitrary REs, creates a regular expression that will match either A or B. An arbitrary number of REs can be separated by the '|' in this way. This can be used inside groups (see below) as well. As the target string is scanned, REs separated by '|' are tried from left to right.

所以你需要做:

expr = re.sub(r"\|\|","_or_",sequence)

或者,使用 re.escape() :感谢 @Steven指出这一点

expr = re.sub(re.escape("||"),"_or_",sequence)

你会得到:

IN : sequence = "if(ab||2) + H) then a*10"
OUT : 'if(ab_or_2) + H) then a*10'

编辑:

如果您不需要仅使用regex,则可以直接使用replace来替换字符串。即,

sequence.replace('||','_or_')

在这里您不必担心特殊字符。

关于python - 如何使用 Regex Python 从序列中查找逻辑 'or' 运算符 (||),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46428131/

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