使用正则表达式 匹配 HTML 标签内的内容

使用正则表达式 匹配 HTML 标签内的内容

正则表达式如下

/(?<=((<[a-zA-Z-]+?){0,1}>))([\s\S]+)(?=([\s]{0,1}<\/[a-zA-Z-]+(>{0,1})))/g

测试例子:

var regexp = /(?<=((<[a-zA-Z-]+?){0,1}>))([\s\S]+)(?=([\s]{0,1}<\/[a-zA-Z-]+(>{0,1})))/g

// (以下都是常见的格式化后的代码)

// 例子1
var str1 = `<div>hello</div>`
console.log(str1.match(regexp))
// ['hello']

// 例子2
var str2 = `<div>
  hello
</div>`
console.log(str2.match(regexp))
// ['\n  hello\n']

// 例子3
var str3 = `<div
>hello</div>`
console.log(str3.match(regexp))
// ['hello']

// 例子4
var str4 = `<div
>hello</div
>`
console.log(str4.match(regexp))
// ['hello']

// 例子5
var str5 = `<div
  class="test"
  id="test"
  onClick="fns"
>
  hello
</div>`
console.log(str5.match(regexp))
// ['\n  hello\n']

介绍

其中,这个正则表达式分为三个部分

  1. (?<=((<[a-zA-Z-]+?){0,1}>))
  2. ([\s\S]+)
  3. (?=([\s]{0,1}<\/[a-zA-Z-]+(>{0,1})))

第一部分用来匹配 开始标签 或者 换行的开始标签的最后一个字符 >
第二部分就是标签内的内容
第三部分是标签的 结束标签 或者 </ 加 标签名

第一部分 (?<=y)x 和第三部分 x(?=y) 用到了零宽断言,感兴趣的可以看这里正则表达式 零宽断言

最后

vscode里面使用正则表达式搜索的话,可以把零宽断言去掉,即:

(((<[a-zA-Z-]+?){0,1}>))([\s\S]+)(([\s]{0,1}<\/[a-zA-Z-]+(>{0,1})))
posted @ 2022-04-07 19:13  hiuman  阅读(1364)  评论(0编辑  收藏  举报