【问题标题】:How to concatenate regex patterns?如何连接正则表达式模式?
【发布时间】:2018-12-17 18:32:40
【问题描述】:

我正在尝试使用字典替换 html 文件中的文本。

这可行,但不幸的是,如果文本被 html 标签包围或旁边有逗号,则与文本不匹配:

for key in dictionary:
    print(key)
    if key in answer_string:
        pattern = re.compile(key, re.IGNORECASE)
        answer_string = re.sub(r"[^ ]*"+pattern+r"[^ ]*", "<a href=\"" + dictionary.get(key) + "\">" + key + "</a>", answer_string)

这是我尝试过但不起作用的方法。我得到错误:TypeError: cannot concatenate 'str' and '_sre.SRE_Pattern' objects

for key in dictionary:
    print(key)
    if key in answer_string:
        pattern = re.compile(key, re.IGNORECASE)
        answer_string = re.sub(r"[^ ]*"+pattern+r"[^ ]*", "<a href=\"" + dictionary.get(key) + "\">" + key + "</a>", answer_string)

【问题讨论】:

    标签: python regex dictionary replace


    【解决方案1】:

    re.compile 返回一个正则表达式编译对象,而不是一个字符串。你只需要在编译之前连接你的字符串:

    for key in dictionary:
        print(key)
        if key in answer_string:
            pattern = re.compile(r"[^ ]*"+key+r"[^ ]*", re.IGNORECASE)
            answer_string = pattern.sub("<a href=\"" + dictionary.get(key) + "\">" + key + "</a>", answer_string)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-07-11
      • 1970-01-01
      • 1970-01-01
      • 2012-02-12
      • 2011-02-12
      • 2012-05-28
      • 1970-01-01
      相关资源
      最近更新 更多