【问题标题】:Replace text inside bracket with an anchor link用锚链接替换括号内的文本
【发布时间】:2025-12-18 20:35:01
【问题描述】:

我目前有这样的正文

text = "hello this [is a cool] line of text that might have [two] brackets.

我需要的是解析和替换这个文本,所以在这个例子中它最终会像

text = "hello this <a href='/phrase/is a cool/'>is a cool</a> line of text that might have <a href='/phrase/two/'>two</a> brackets.

现在我认为在正则表达式中找到所有括号都是\[.*?\],但我不确定如何具体执行此操作。

【问题讨论】:

  • 你能用{}代替[]吗?
  • @Jortega 我想
  • 好了,现在我们可以使用.format,省力了。
  • 这有帮助吗? *.com/questions/11096720/…

标签: python


【解决方案1】:

你可以这样做:

import re

text = "hello this [is a cool] line of text that might have [two] brackets."

brackets = re.compile(r'\[(.*?)\]')
new_text = brackets.sub(lambda x: f'<a href=/phrases/{x.group(1)}>{x.group(1)}</a>', text)

print(new_text)

这将用 lambda 返回的内容替换模式:
x.group(1) 返回正则表达式模式中的第一组(索引从 1 开始):(.*?),这意味着它将仅返回括号和然后使用f strings对其进行格式化。

还可以使用此代码从括号中的文本中删除任何标点符号(注意最终结果如何没有括号之间的任何.):

import re
import string

text = "hello this [is a..... cool] line of text that might have [two] brackets."


def replace_with_link(match):
    info = match.group(1)
    info = info.translate(str.maketrans('', '', string.punctuation))
    return f'<a href="/phrases/{info}">{info}</a>'


brackets = re.compile(r'\[(.*?)\]')
new_text = brackets.sub(replace_with_link, text)

print(new_text)

【讨论】:

  • 谢谢,我想如果括号内有逗号或句点等特殊字符,这会将它们留在里面还是去掉它们?如果是这样,有什么方法可以剥离它们?
  • @nadermx @nadermx 很好 . 匹配任何字符(换行符除外)并且不会真正排除任何内容,我将编辑添加如何删除所有标点符号,如果这是您正在寻找的内容跨度>
  • @nadermx 我已经添加了标点符号的代码,我很确定我写了一条评论,但现在我没有看到它,所以以防万一我写了这个
【解决方案2】:

您可以通过以下方式做到这一点

  1. 获取[]包围的所有子字符串
  2. 用适当的文字替换内容
>>> import re
>>> txt = "hello this [is a cool] line of text that might have [two] brackets."
>>> phrases = re.findall(r"(\[.+?\])", txt)
>>> for phrase in phrases:
...     txt = txt.replace(phrase, "<a href='/phrase/{}/'>{}</a>".format(phrase[1:-1], phrase[1:-1]))
... 
>>> txt
"hello this <a href='/phrase/is a cool/'>is a cool</a> line of text that might have <a href='/phrase/two/'>two</a> brackets."
>>> 

【讨论】: