我已经编写了一个正则表达式来匹配子字符串及其周围的空格,但效果不佳

I have written a regex for matching the sub string with spaces around it but that's not working well

实际上,我正在研究一个正则表达式问题,其任务是获取一个子字符串 (||, &&) 并将其替换为另一个子字符串 (or, and),我为此编写了代码,但效果不佳

question = x&& &&& && && x || | ||\|| x
Expected output = x&& &&& and and x or | ||\|| x

这是我写的代码

import re
for i in range(int(input())):
    print(re.sub(r'\s[&]{2}\s', ' and ', re.sub(r"\s[\|]{2}\s", " or ", input())))

我的输出= x&& &&& and && x or | ||\|| x

你需要使用 lookarounds,当前正则表达式的问题是 && && 这里 && 第一个匹配捕获 space 所以之前没有 space第二个 && 不匹配,所以我们需要使用 zero-length-match ( lookarounds)

替换正则表达式

\s[&]{2}\s  -->  (?<=\s)[&]{2}(?=\s)
\s[\|]{2}\s -->    (?<=\s)[\|]{2}(?=\s)

(?<=\s) - 匹配应在 space 个字符之前

(?=\s) - 匹配应后跟 space 个字符

您正在寻找像 (?<=\s)&&(?=\s) (Regex demo)

这样的正则表达式

使用环视断言目标替换组周围 space 个字符的位置允许出现重叠匹配 - 否则,它将匹配两侧的 space 并阻止其他选项.

import re

in_str = 'x&& &&& && && x || | ||\|| x'
expect_str = 'x&& &&& and and x or | ||\|| x'

print(re.sub("(?<=\s)\|\|(?=\s)", "or", re.sub("(?<=\s)&&(?=\s)", "and", in_str)))

Python demo

尝试使用 re.findall() 而不是 re.sub