我希望文本中看起来像<Bus:1234|Bob Alice>
或<Car:5678|Nelson Mandela>
的所有标记分别替换为<a my-inner-type="CR:1234">Bob Alice</a>
和<a my-inner-type="BS:5678">Nelson Mandela</a>
。所以基本上,根据类型是TypeA
还是TypeB
,我想用Python3和regex相应地替换文本字符串中的文本。你知道吗
我尝试用python执行以下操作,但不确定这是否是正确的方法:
import re
def my_replace():
re.sub(r'\<(.*?)\>', replace_function, data)
在上面,我尝试对< >
标记和找到的每个标记执行regex,然后将其传递给一个名为replace_function
的函数,在标记之间分割文本,确定它是TypeA
还是TypeB
,并计算内容并动态返回替换标记。我甚至不确定使用re.sub
是否可以这样做,但任何线索都会有所帮助。非常感谢。你知道吗
示例:
<Car:1234|Bob Alice>
变成<a my-inner-type="CR:1234">Bob Alice</a>
<Bus:5678|Nelson Mandela>
变成<a my-inner-type="BS:5678">Nelson Mandela</a>
抱歉,这不是一个完整的答案,但我在电脑前睡着了,但这是正则表达式,它将匹配您提供的任何字符串
(<Type)(\w:)(\d+\|)(\w+\s\w+>)
。查看https://pythex.org/测试您的正则表达式。你知道吗可能是@swalladge答案的扩展,但这里我们使用字典的优势,如果我们知道映射的话。(请考虑使用自定义映射函数替换字典。你知道吗
输出
工作示例here。你知道吗
正则表达式 我们在3个组中捕获我们需要的内容,并通过match object引用它们。粗体突出显示的是我们在regex中捕获的3个组。
<
(.*?)
(:\d+)
\|
(.*?)
>
我们在
repl
函数中使用这3个组来返回正确的字符串。你知道吗这在
re.sub
中是完全可能的,并且使用替换函数(设计为允许动态替换)是正确的。请参阅下面的示例,了解与您给出的示例一起工作的示例-可能需要根据文本中存在的其他数据(即需要忽略的其他标记)进行修改以适合您的用例警告:如果此文本实际上是完整的html,正则表达式匹配将不可靠-请使用类似beautifulsoup的html处理器。;)
相关问题 更多 >
编程相关推荐