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

标签 python regex regular-language

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

以下是代码,我正在尝试

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/

相关文章:

python - 在模板中渲染外键列表

python - IE 测试的 Selenium 问题

python - 如何在不创建临时列的情况下从 pandas 数据框列计算最小值?

regex - R中的匹配和计数字符串(DNA的k-mer)

regex - 过滤特殊字符的正则表达式不起作用

python - 尽可能远离陆地 - DP 解决方案

python - 使用正则表达式将韩文文本解析为列表

PHP正则表达式将嵌套()替换为[]

math - 确保: Pumping lemma for infinite regular languages only?

computer-science - 什么是规律性?