2013-05-28 39 views
0

我一直在为这似乎是一辈子的代码,似乎无法得到它的工作。Python:re.sub模式和替换通配符

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>,同时保持所有内部文本相同。任何人都可以请指教?

预先感谢您!

回答

0

这做几乎你想要什么:

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

[^\]]采取\[ clsing支架后,除了每个字符。

随着该#它是这样的:

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

.总是有点问题的,如果你想找到的东西之间的事情。

+0

谢谢,这解决了这个问题。 – user2421580