我需要按类和一些属性值捕获 html 标签。
我已经解决了第一部分,按类捕获标签( querySelector
应该类似于: 'input.hashtag'
):
<input type="text" value="#tag3" notified="true" class="label-primary hashtag">
所以,我使用这个正则表达式:
/(?=<input[^>]+(?=[\s+class=\"]hashtag[\s+\"]).+)([^>]+>)/g
您可以在此处查看测试 https://regex101.com/r/zY4sH9/6
我需要的是还捕获属性值:value
和nofified
,最终得到:
- 比赛1
<input type="text" value="#tag3" notified="true" class="label-primary hashtag">
- 比赛2
#tag
- 比赛3
true
最佳答案
您说过您已经在使用 .querySelector()
方法,因此我建议避免使用正则表达式并使用 native DOM 方法。
var element = document.querySelector('input.hashtag'),
value = element.value,
notified = element.getAttribute('notified');
同样,如果您想选择input
具有 .hashtag
的元素类和 value
/notified
属性,那么您可以简单地使用两个属性选择器 input.hashtag[value][notified]
:
var element = document.querySelector('input.hashtag[value][notified]'),
value = element.value,
notified = element.getAttribute('notified');
<小时/>
但是,如果您需要使用正则表达式,则以下内容将捕获 value
和notified
属性的值无论顺序如何(因为正在使用正向前瞻):
/(<input(?=[^>]*[\s+class=\"]hashtag[\s+\"])(?=[^>]*value=\"([^"]+)\")(?=[^>]*?notified=\"([^"]+)\")[^>]*\>)/
我只是根据您现有的表达式构建的,所以我不需要解释第一部分。
(?=[^>]*value=\"([^"]+)\")
- 使用捕获组进行正向预测以匹配value
零个或多个非>
之后的属性值字符。(?=[^>]*?notified=\"([^"]+)\")
- 使用捕获组进行正向预测以匹配notified
零个或多个非>
之后的属性值字符。
捕获组:
第 1 组 - <input type="text" value="#tag3" notified="true" class="label-primary hashtag">
第 2 组 - #tag3
第 3 组 - true
关于JavaScript 正则表达式 : Find a tag and get some attribute values,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34994532/