python - 正则表达式捕获带有逗号或点的数字,除非在标记之间

python - regex to capture a number with comma or a dot unless between tokens

我想用以下格式之一替换数字: 200, 200.99, 300,555 除非它在 ​​<> 标记之间。 例如我想跳过这个: <200>

这是我想出的:

(?<!<)([\d,|.]+(?:\.\d{2})?)(?!>)

通过在 regex101 中对其进行测试,我只跳过了 < 之后和 > 之前的第一个和最后一个数字。

我正在逐行遍历文本文件,我想替换所有出现的以下示例:

200
200.00
200.000

带有标记,但如果该行在 <> 之间已经有一个数字,则跳过该行,澄清一下,我想跳过我行中的以下值,而不是用正则表达式替换:

<300>

这是我使用的代码:

current_line = re.sub("(?<!<)([\d,|.]+(?:\.\d{2})?)(?!>)", ' <num> ', current_line)

你能帮忙吗?

这不是满足您要求的精确解决方案,但如果您将负面环视更改为正面环视,即断言数字两边都被空格或 starting/ending 锚点包围,那么您似乎得到了你想要的行为:

rx = r"(\s|^)([\d,|.]+(?:\.\d{2})?)(?=$|\s)"
s = "I would like to replace a number with one of the following formats: 200, 200.99, 300,555 unless its between the <> tokens. for example I would like to skip this: <200>"
print(re.findall(rx, s))

[(' ', '200,'), (' ', '200.99,'), (' ', '300,555')]

Demo

(由 Wiktor 提供)

它的一个限制是它不会匹配 <234 之类的字词,因为数字没有被包围在 whitespace/anchors 两边。但是,该模式确实正确地排除了标签中包含的数字。