9

我想替换字符串句子中的单词,例如:

What $noun$ is $verb$?

用实际名词/动词替换“$ $”(包括)中的字符的正则表达式是什么?

4

4 回答 4

20

您不需要正则表达式。我会做

string = "What $noun$ is $verb$?"
print string.replace("$noun$", "the heck")

仅在需要时使用正则表达式。一般比较慢。

于 2012-09-21T21:15:52.057 回答
5

鉴于您可以$noun$根据自己的喜好自由修改等,现在执行此操作的最佳实践可能是format在字符串上使用该函数:

"What {noun} is {verb}?".format(noun="XXX", verb="YYY")
于 2015-10-19T08:42:54.797 回答
1
In [1]: import re

In [2]: re.sub('\$noun\$', 'the heck', 'What $noun$ is $verb$?')
Out[2]: 'What the heck is $verb$?'
于 2012-09-21T21:13:27.707 回答
0

使用字典来保存正则表达式模式和值。使用 re.sub 替换令牌。

dict = {
   "(\$noun\$)" : "ABC",
   "(\$verb\$)": "DEF"
} 
new_str=str
for key,value in dict.items():
   new_str=(re.sub(key, value, new_str))
print(new_str)

输出:

What ABC is DEF?
于 2021-07-02T20:09:30.417 回答