简体   繁体   English

python中的Re.sub不起作用

[英]Re.sub in python not working

Suppose that: 假设:

s = '<A HREF="http://www.google.com" ID="test">blah</A>'

I want to prepend the url with "url: ", so I tried: 我想在URL前面加上“ url:”,所以我尝试了:

s = re.sub(r'href="([\w:/.]+)"', "url: " + r'\1', s, re.I)

but this does not change s . 但这不会改变s

The re.I is in the wrong position (it's being interpreted as the count argument). re.I位置错误(被解释为count参数)。

From the documentation : 文档中

re.sub(pattern, repl, string, count=0, flags=0)
                              ^^^^^    ^^^^^

Try: 尝试:

In [27]: re.sub(r'href="([\w:/.]+)"', "url: " + r'\1', s, flags=re.I)
Out[27]: '<A url: http://www.google.com ID="test">blah</A>'

While the other answer is technically absolutely correct, I don't think you want that what is mentionned there. 尽管另一个答案在技术上绝对是正确的,但我认为您不希望在那里提到的内容。

Instead, you might want to work with a match object: 相反,您可能想使用匹配对象:

m = re.search(r'href="([\w:/.]+)"', s, re.I)
print m.expand(r"url: \1")

which results to 导致

url: http://google.com

without the <A before and the ID="test">blah</A> behind. 前面没有<A ,后面没有ID="test">blah</A>

(If you want to do more of these replacements, you might even want to reuse the regex by compiling it: (如果您想进行更多此类替换,您甚至可能希望通过编译来重用正则表达式:

r = re.compile(r'href="([\w:/.]+)"', re.I)
ex = lambda st: r.search(st).expand(r"url: \1")
print ex('<A HREF="http://www.google.com" ID="test">blah</A>')
print ex('<A HREF="http://www.yahoo.com" ID="test">blah</A>')
# and so on.

If, however, you indeed want to keep the HTML around it, you'll have to work with lookahead and lookbehind expressions: 但是,如果确实要保留HTML,则必须使用超前和后向表达式:

re.sub(r'(?<=href=")([\w:/.]+)(?=")', "url: " + r'\1', s, flags=re.I)
# -> '<A HREF="url: http://www.google.com" ID="test">blah</A>'

or simply by repeating the omitted stuff: 或简单地通过重复省略的内容:

re.sub(r'href="([\w:/.]+)"', r'href="url: \1"', s, flags=re.I)
# -> '<A href="url: http://www.google.com" ID="test">blah</A>'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM