python-3.x - 需要找到完全匹配并使用正则表达式替换

标签 python-3.x regex

我有一个输入,需要将 && 替换为 and

注意: && 作为左右空格,输出也应包含左右空格

输入:

s = 'n && && && && && &&n'

我的代码:

m=re.sub(r'\s[&&]\s', ' and ',s)
print(m)

我的输出:

n && && && && && &&n

预期输出:

n and and and and and &&n

最佳答案

我会在 (?<!\S)&&(?!\S) 上进行正则表达式替换:

import re

s = 'n && && && && && &&n'
output = re.sub(r'(?<!\S)&&(?!\S)', 'and', s)
print(output)  # n and and and and and &&n

这里的正则表达式模式表示匹配:

  • (?<!\S)断言前面是空格或输入的开头
  • &&匹配文字 &&
  • (?!\S)断言后面的内容是空格或输入的结尾

关于python-3.x - 需要找到完全匹配并使用正则表达式替换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76294931/

相关文章:

python - 使用线程读取文件并传递数据

python - 从 flask 中的 mysql 提取信息时出现问题

python - pandas 将标题与行进行比较并删除重复的行

regex - 使用 awk 解析带有空字段、转义引号和逗号的 CSV

Javascript:如何剪切字符串的特定部分?

C++ 正则表达式排除双引号不起作用

python-3.x - 导入错误 : DLL load failed while importing IfxPy on Windows with Python3. 8

python - Keras 中的 "Could not interpret optimizer identifier"错误

Javascript:用于从样式字符串替换 translate3d 字符串的正则表达式

mysql - 用于检查 JSON 数组中是否存在至少一项的 SQL 正则表达式