我无法从re.compile
的html中找到所有的<script>.*</script>
。
以下是re
文档中的一个示例:
import re
result = re.findall(r'(w+)=(d+)', 'set width=20 and height=10')
print("type: {}, len: {}, values: {}".format(type(result), len(result), result))
print("type: {}, len: {}, values: {}".format(type(result[0]), len(result[0]), result[0]))
输出如下:
type: <class 'list'>, len: 2, values: [('width', '20'), ('height', '10')]
type: <class 'tuple'>, len: 2, values: ('width', '20')
下面是我的测试示例:
import re
string = (
'which <script> prefix foot suffix </script> '
'or <script> prefix hand suffix </script> fell fastest'
)
result = re.findall(r'<script>', string)
print("type: {}, len: {}, values: {}n".format(type(result), len(result), result))
result = re.findall(r'</script>', string)
print("type: {}, len: {}, values: {}n".format(type(result), len(result), result))
result = re.findall(r'<script>.*</script>', string)
print("type: {}, len: {}, values: {}n".format(type(result), len(result), result))
输出如下:
type: <class 'list'>, len: 2, values: ['<script>', '<script>']
type: <class 'list'>, len: 2, values: ['</script>', '</script>']
type: <class 'list'>, len: 1, values: ['<script> prefix foot suffix </script> or <script> prefix hand suffix </script>']
问题1:
我想找出<script>
和</script>
之间的所有文本,并包括标签本身。
这是预期的输出,结果应该包含列表中的2项,其值如下:
<script> prefix foot suffix </script>
<script> prefix hand suffix </script>
问题2:
然后,我想替换包含"foot"的匹配;使用空字符串,然后返回最终的html:
<script> prefix foot suffix </script> ----> ""
我尝试了一些模式,但没有成功。如何做到这一点?
在您的情况下,您正在匹配第一个<script>
标记与最后一个</script>
标记以及之间的所有内容与贪婪的.*
。您需要做的是通过在它后面添加?
来使它变为惰性:
result = re.findall(r'<script>.*?</script>', string)
* ?在0到无限次之间匹配前一个标记,尽可能少地匹配,根据需要展开(惰性)
result
变量将拥有两个字符串的数组。至于你的第二个问题,您可以简单地遍历这个数组,使用re.sub
替换字符串:
for r in result:
if "foot" in r:
r = re.sub(r'<script>(.*?)</script>', "<script></script>", r)
print(r)