我有许多html代码,它们有<pre> python code </pre>
,如下所示
html代码:
<pre class="c1">
# regex usage
import re
re.findall(r'abc','abcde')
</pre>
python tutorial ...python regex<br>
<pre class="c2">
# regex usage
import re
re.findall(r'abc','abcde')
</pre>
我将regex
视为关键字,并将其替换为链接:<a href="link-to-regex">regex</a>
,但我不想替换标签<pre>
中的内容
输出:
<pre class="c1">
# regex usage
import re
re.findall(r'abc','abcde')
</pre>
python tutorial ...python <a href="link-to-regex">regex</a><br>
<pre class="c2">
# regex usage
import re
re.findall(r'abc','abcde')
</pre>
我用占位符来做
pre_list = re.compile(r'(<pre>.+?</pre>)').findall(html_code)
# use CODE_PLACEHODER to protect code sources
for index,code in enumerate(pre_list):
html_code = html_code.replace(code, 'CODE_PLACEHOLDER_{}'.format(index))
# replace the html content here
html_code = html_code.replace('regex', '<a href="link-to-regex">regex</a>')
for index,code in enumerate(pre_list):
html_code = html_code.replace('CODE_PLACEHOLDER_{}'.format(index), code)
enter code here
有更好的方法吗?你知道吗
使用肯定的lookaround断言来匹配字符串
regex
,该字符串不在<pre>
标记中。别忘了启用DOTALL修饰符。你知道吗DEMO
试试看这个。看到了吗演示。你知道吗
http://regex101.com/r/rQ6mK9/8
相关问题 更多 >
编程相关推荐