在字符串中
x='(var1 * 1.3e4 + abc)/log(blabla+2E3)'
我想用var1
替换abc
,blabla
和'1'
,说要传入ast
,看看这是否是一个正确的表达。我不想触摸log
或e
或E
。当然还有其他我想跳过的东西,比如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
。
\b(?!(?:[+-]?\d*\.?\d+(?:e[+-]?\d+)?|log|sin|cos)\b)\w+\b
创建一个例外数组(如下所示)并加入|
上的列表。另外,请注意re.escape
并不总是必要的,但我想我会展示它如何用正常的字符串和正则表达式创建这个连接列表(如果你需要这样做的话)。
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)
这包含加入的例外列表,如log
,sin
,cos
或数字([+-]?\d*\.?\d+(?:e[+-]?\d+)?
)等。\w+
匹配一个或多个单词字符\b
将位置断言为单词边界