2

I am trying to replace all expressions of the form

\[something\]

in a string by

\[<img src='something'>\]

Since \ and [ ] are special characters, I need to espace them (so \\, \[ and \]), thus my code would be

def repl(m):
    return "<img src='"+m.group(1)+"'>"

print re.sub("\\\[(.*?)\\\]", repl, "frfrfr\nfrrffr<p>\[something\]</p>frff\nfrfrr", re.S)

However, this returns the original string. Could someone point out my mistake ?

4

1 回答 1

5

正确转义\,或r'raw string'如下使用。

>>> print re.sub(r"\\\[(.*?)\\\]", repl, "frfrfr\nfrrffr<p>\[something\]</p>frff\nfrfrr", flags=re.S)
frfrfr
frrffr<p><img src='something'></p>frff
frfrr

>>> print re.sub("\\\\\\[(.*?)\\\\\\]", repl, "frfrfr\nfrrffr<p>\[something\]</p>frff\nfrfrr", flags=re.S)
frfrfr
frrffr<p><img src='something'></p>frff
frfrr

更新

的第四个参数re.subcount,不是flags。要指定标志,请使用关键字参数。否则,re.S被识别为count

>>> print re.sub(r"\\\[(.*?)\\\]", repl, "frfrfr\nfrrffr<p>\[something\nblah\]</p>frff\nfrfrr", re.S)
frfrfr
frrffr<p>\[something
blah\]</p>frff
frfrr
>>> print re.sub(r"\\\[(.*?)\\\]", repl, "frfrfr\nfrrffr<p>\[something\nblah\]</p>frff\nfrfrr", flags=re.S)
frfrfr
frrffr<p><img src='something
blah'></p>frff
frfrr
于 2013-11-05T15:22:45.730 回答