匹配除特定少数之外的所有单词用于替换目的,数学表达式用例

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

在字符串中

x='(var1 * 1.3e4 + abc)/log(blabla+2E3)'

我想用var1替换abcblabla'1',说要传入ast,看看这是否是一个正确的表达。我不想触摸logeE。当然还有其他我想跳过的东西,比如sin

目前我正在使用类似的东西

for match in re.findall(r'[a-zA-Z]+',x):
    if match.startswith('log') or match.lower()=='e': continue
    x = x.replace(string,'1')

日志可以有几种口味,因此startswith - 显然不适用于任何情况。我宁愿一次性使用re.sub

python regex
1个回答
2
投票

See regex in use here

\b(?!(?:[+-]?\d*\.?\d+(?:e[+-]?\d+)?|log|sin|cos)\b)\w+\b

Usage

创建一个例外数组(如下所示)并加入|上的列表。另外,请注意re.escape并不总是必要的,但我想我会展示它如何用正常的字符串和正则表达式创建这个连接列表(如果你需要这样做的话)。

See code in use here

import re

exceptions = [
    re.escape("log"),
    re.escape("sin"),
    re.escape("cos"),
    r"[+-]?\d*\.?\d+(?:e[+-]?\d+)?"
]

s = "(var1 * 1.3e4 + abc)/log(blabla+2E3)*1.2E+23"
r = r"\b(?!(?:" + "|".join(exceptions) + r")\b)\w+\b"

print re.sub(r, "1", s, 0, re.I)

说明

  • \b将位置断言为单词边界
  • (?!(?:stuff here)\b)负向前瞻确保后面的内容不匹配 (?:stuff here)这包含加入的例外列表,如logsincos或数字([+-]?\d*\.?\d+(?:e[+-]?\d+)?)等。
  • \w+匹配一个或多个单词字符
  • \b将位置断言为单词边界
© www.soinside.com 2019 - 2024. All rights reserved.