regex一个字符串,在单词之间有空间

问题描述 投票:0回答:1
import re

texto = "ABC ABC. ABC.png ABC thumb.png"

regex = r"ABC(?!.png)|ABC(?! thumb.png)"

novo = re.sub(regex, "bueno", texto)

print(novo)
我正在尝试用异常替换ABC单词。我只想在不遵循“ .png”或“ thumb.png”一词时替换它。然后将字符串为“ abc thumb.png”

我期望

bueno bueno. ABC.png ABC thumb.png

,但输出是这个

bueno bueno. bueno.png bueno thumb.png

它没有检测到空间,而实际上会弄乱第一个条件。
    

或(
python regex
1个回答
0
投票
)需要在负面的lookahead内部:

ABC(?!.png| thumb.png)

LLET以sudstring为例,作为您原始图案发生的事情的一个例子。 Regex引擎将首先尝试使用
ABC.png
匹配,这将由于负面的lookahead而失败。然后,由于OR,它将跳到下一个情况下。这将匹配

ABC(?!.png)

,这意味着字符串将被替换。
    

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.