我写了一个正则表达式,用于将子字符串与它周围的空格匹配,但是效果不佳

问题描述 投票:1回答:4

实际上,我正在处理一个正则表达式问题,其任务是获取一个子字符串(||,&&)并用另一个子字符串(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 && &&&&和&& x或| || \ || x

regex python-3.x regex-lookarounds substitution
4个回答
1
投票

[您需要使用环顾四周,当前正则表达式的问题是&& &&,此处&&第一个匹配项捕获了空间,因此第二个&&之前没有可用空间,因此将不匹配,因此我们需要使用zero-length-match ( lookarounds)

替换正则表达式

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

[(?<=\s)-匹配项应在空格字符前]

[(?=\s)-匹配项后应跟空格字符


0
投票

您正在寻找正则表达式,例如(?<=\s)&&(?=\s) (Regex demo)

使用环视方法来断言目标替换组周围的空格字符的位置会导致重叠的匹配发生-否则,它将在两侧匹配空格并阻止其他选项。

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


0
投票

尝试使用re.findall()代替re.sub

© www.soinside.com 2019 - 2024. All rights reserved.