如何使用正则表达式 Python 从序列中查找逻辑 'or' 运算符 (||)

How to find logical 'or' operator (||) from a sequence using Regex Python

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

代码如下,我正在尝试

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

你需要在这里使用escape sequence'\'因为'|'是一个特殊字符。

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():感谢 指出这一点

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_')

在这里你不用担心特殊字符。