0

我一直在编写这段代码,这似乎是一辈子的事情,但似乎无法让它发挥作用。

pattern = "\[([a-zA-Z0-9].*?)#([a-zA-Z0-9].*?)\]"
pattern_obj = re.compile(pattern, re.MULTILINE)
translation = pattern_obj.sub("<ol>\\1</ol>", translation)

我在这里要做的是更改一些文本,即:

[ 
  # This is item number one in an ordered list. #

  # And this is item number two in the same list. #
]

进入:

<ol> 
#This is item number one in an ordered list. #
#And this is item number two in the same list. #
</ol>

本质上,它应该在文本中的某处用 # 标识 [ 和 ] 之间的任何文本,并将 [<ol>和 ] 更改为</ol>同时保持所有内部文本相同。有人可以请教吗?

先感谢您!

4

1 回答 1

0

这几乎可以满足您的要求:

>>> re.compile(r"\[([^\]]*)\]").sub("<ol>\\1</ol>", "b[#a]c")
'b<ol>#a</ol>c'

在clsing 括号之后获取除 ] 之外的[^\]]每个字符。\[

使用 a#它看起来像这样:

>>> 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'

如果你想在某事之间找到一些东西,那.总是有点问题。

于 2013-05-28T16:26:56.983 回答