簡體   English   中英

Python:re.sub模式和替換通配符

[英]Python: re.sub pattern and replacement wildcard

我一直在走這段代碼,看起來似乎是一輩子的,似乎無法使其正常工作。

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> 任何人都可以請教嗎?

先感謝您!

這幾乎可以滿足您的要求:

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

. 如果您想在某物之間找到某物,總是有點問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM