Python正则表达式替换锚点

2024-06-25 06:38:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图重写我在this中看到的代码答案:

import re

pat1 = re.compile(r"(^|[\n ])(([\w]+?://[\w\#$%&~.\-;:=,?@\[\]+]*)(/[\w\#$%&~/.\-;:=,?@\[\]+]*)?)", re.IGNORECASE | re.DOTALL)

pat2 = re.compile(r"#(^|[\n ])(((www|ftp)\.[\w\#$%&~.\-;:=,?@\[\]+]*)(/[\w\#$%&~/.\-;:=,?@\[\]+]*)?)", re.IGNORECASE | re.DOTALL)


urlstr = 'http://www.example.com/foo/bar.html'

urlstr = pat1.sub(r'\1<a href="\2" target="_blank">\3</a>', urlstr)
urlstr = pat2.sub(r'\1<a href="http:/\2" target="_blank">\3</a>', urlstr)

print urlstr

具体地说,我试过:

^{pr2}$

我想替换这样的东西:

<a href="javascript:rt(2061)">Download</a>

有了这个:

2061

我也希望这样做:

<a href="#" onclick="javascript:ra('Name of object one')"
  title="Some title Text">Name of Object two</a>

与正义

Name of Object two

通过做

pattern = re.compile('<a href="#" onclick="javascript:ra\('(:?[a-zA-Z0-9 +)'\)" title="Some title Text">([a-zA-Z0-9 ]+)</a>');

rawtable = pattern.sub(r'\1', rawtable) 

但也不管用。有什么提示吗?在


Tags: ofnamerehttptargettitlewwwjavascript
1条回答
网友
1楼 · 发布于 2024-06-25 06:38:00

where I want to replace something like this:

<a href="javascript:rt(2061)">Download</a>

你的第一个密码有效。Test here



I'd like to do the same with this:

<a href="#" onclick="javascript:ra('Name of object one')" title="Some title Text">Name of Object two</a>`

至于第二个,检查一下我在这里做的标记:

pattern = re.compile('<a href="#" onclick="javascript:ra\('(:?[a-zA-Z0-9 +)'\)" title="Some title Text">([a-zA-Z0-9 ]+)</a>');
                                                          | | |         |  ^ unescaped quote (in the string passed to re.compile() )
                                                          | | |         |
                                                          | | ^    -^ you didn't close the character class (as in [a-z]).. add a "]"
                                                          | ^ correct syntax is (?: pattern ) ... However, no point in using it here
                                                          ^ another unescaped quote

代码:

^{pr2}$

Run this code

输出:

Name of Object two

相关问题 更多 >