怎样只把标签代码改为小写?

2016-11-30 13:41:56 +08:00
 omg21
我想把<>标签代码改成小写,其余部分不变应该怎么写?
比如把<DIV>Windows XP</DIV>改成<div>Windows XP</div>

想用正则替换,但是没想好应该怎么做。
pattern = re.compile(r'<!--(.*?)/-->',re.I|re.S)
htmlstr = re.sub(pattern,'',htmlstr)
1685 次点击
所在节点    Python
3 条回复
halfcrazy
2016-11-30 14:11:06 +08:00
```python
# -*- coding: utf-8 -*-
import re

pattern = "</?(\w+)>"
txt = "<DIV>Windows XP</DIV><A>Windows XP</A><script>Windows XP</script>"


def _sub(matchobj):
return matchobj.group(0).replace(matchobj.group(1),
matchobj.group(1).lower())

print(re.sub(pattern, _sub, txt))

```
halfcrazy
2016-11-30 14:22:56 +08:00
@halfcrazy 考虑到存在单标签的情况。正则式需要修改一下`pattern = "</?(\w+)(?:[\s\S])*?/?>"`
omg21
2016-11-30 14:27:12 +08:00
@halfcrazy 谢谢,这要让我自己想,想三天也想不出来个结果

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/324330

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX