Python:re.sub模式和替换通配符
我花了一辈子的时间编写这段代码,但似乎无法让它正常工作Python:re.sub模式和替换通配符,python,design-patterns,replace,Python,Design Patterns,Replace,我花了一辈子的时间编写这段代码,但似乎无法让它正常工作 pattern = "\[([a-zA-Z0-9].*?)#([a-zA-Z0-9].*?)\]" pattern_obj = re.compile(pattern, re.MULTILINE) translation = pattern_obj.sub("<ol>\\1</ol>", translation) 进入: #这是有序列表中的第一项# #这是同一清单中的第二项# 本质上,它应该在文本中的某个地方用#
pattern = "\[([a-zA-Z0-9].*?)#([a-zA-Z0-9].*?)\]"
pattern_obj = re.compile(pattern, re.MULTILINE)
translation = pattern_obj.sub("<ol>\\1</ol>", translation)
进入:
#这是有序列表中的第一项#
#这是同一清单中的第二项#
本质上,它应该在文本中的某个地方用#标识[和]之间的任何文本,并将[改为
和]改为
,同时保持所有内部文本不变。有人能给我建议吗
提前谢谢你 这几乎满足了您的需求:
>>> re.compile(r"\[([^\]]*)\]").sub("<ol>\\1</ol>", "b[#a]c")
'b<ol>#a</ol>c'
如果你想在两者之间找到某种东西,
总是有点问题
<ol>
#This is item number one in an ordered list. #
#And this is item number two in the same list. #
</ol>
>>> re.compile(r"\[([^\]]*)\]").sub("<ol>\\1</ol>", "b[#a]c")
'b<ol>#a</ol>c'
>>> re.compile(r"\[([^\]]*#[^\]]*)\]").sub("<ol>\\1</ol>", "b[#a]c")
'b<ol>#a</ol>c'
>>> re.compile(r"\[([^\]]*#[^\]]*)\]").sub("<ol>\\1</ol>", "b[gggg]c")
'b[gggg]c'