【问题标题】:Use a variable name in re.sub [duplicate]在 re.sub 中使用变量名 [重复]
【发布时间】:2019-10-29 05:13:19
【问题描述】:

我有一个函数,我使用正则表达式替换句子中的单词。

我的功能如下:

def replaceName(text, name):
    newText = re.sub(r"\bname\b", "visitor", text) 
    return str(newText)

举例说明:

text = "The sun is shining"
name = "sun"

print(re.sub((r"\bsun\b", "visitor", "The sun is shining"))

>>> "The visitor is shining"

但是:

replaceName(text,name)
>>> "The sun is shining"

我认为这不起作用,因为我使用的是字符串的名称(在本例中为名称)而不是字符串本身。谁知道我该怎么做才能使这个功能起作用?

我考虑过:

  1. Using variable for re.sub, 然而,尽管名称相似,但它是一个不同的问题。
  2. Python use variable in re.sub,但这只是日期和时间。

【问题讨论】:

  • re.sub(r"\b{}\b".format(name), "visitor", text)re.sub(rf"\b{name}\b", "visitor", text) 在 Python 3.7+ 中。 re.escape 和其他调整也应该考虑。

标签: python regex function replace


【解决方案1】:

您可以在这里使用字符串格式:

def replaceName(text, name):
    newText = re.sub(r"\b{}\b".format(name), "visitor", text) 
    return str(newText)

否则,在您的情况下,re.sub 只是在寻找完全匹配的 "\bname\b"


text = "The sun is shining"
name = "sun"
replaceName(text,name)
# 'The visitor is shining'

或者对于3.6< 的python 版本,您可以使用@wiktor 在cmets 中指出的f-strings

def replaceName(text, name):
    newText = re.sub(rf"\b{name}\b", "visitor", text) 
    return str(newText)

【讨论】:

    猜你喜欢
    • 2020-06-08
    • 2020-09-22
    • 2013-08-23
    • 2019-04-20
    • 2020-10-16
    • 1970-01-01
    • 1970-01-01
    • 2020-02-20
    • 2021-10-22
    相关资源
    最近更新 更多