gpt4 book ai didi

html - 属性html之间没有空格的正则表达式

转载 作者:太空狗 更新时间:2023-10-29 15:49:01 25 4
gpt4 key购买 nike

如何检测属性之间没有空格。示例:

 <div style="margin:37px;"/></div>
<span title=''style="margin:37px;" /></span>
<span title="" style="margin:37px;" /></span>
<a title="u" hghghgh title="j" >

<a title=""gg ff>

正确:1,3,4不正确:2,5如何检测不正确?

我试过这个:

<(.*?=(['"]).*?\2)([\S].*)|(^/)>

但它不起作用。

最佳答案

You should not use regex to parse HTML ,除非出于学习目的。


http://regexr.com/3cge1

<\w+(\s+[\w-]+(=(['"]?)[^"']*\3)?)*\s*/?>

即使您根本没有任何属性,此正则表达式也会匹配。它适用于自闭合标签,如果属性没有值。


  • <\w+比赛开幕<\w字符。

  • (\s+[\w-]+(=(['"])[^"']*\3)?)*必须以空格开头的零个或多个属性。它包含两部分:

    • \s+[\w-]+必填空格后的属性名
    • (=(['"])[^"']*\3)?可选属性值
  • \s*/?>可选的空格和可选的 /随后关闭> .


这是对字符串的测试:

var re = /<\w+(\s+[\w-]+(=(['"]?)[^"']*\3)?)*\s*\/?>/g;

! '<div style="margin:37px;"/></div>'.match(re);
false

! '<span title=\'\'style="margin:37px;" /></span>'.match(re);
true

! '<span title="" style="margin:37px;" /></span>'.match(re);
false

! '<a title="u" hghghgh title="j" >'.match(re);
false

! '<a title=""gg ff>'.match(re);
true

显示所有不正确的标签:

var html = '<div style="margin:37px;"></div> <span title=\'\'style="margin:37px;"/><a title=""gg ff/> <span title="" style="margin:37px;" /></span> <a title="u" hghghgh title="j"example> <a title=""gg ff>';
var tagRegex = /<\w+[^>]*\/?>/g;
var validRegex = /<\w+(\s+[\w-]+(=(['"]?)[^"']*\3)?)*\s*\/?>/g;

html.match(tagRegex).forEach(function(m) {
if(!m.match(validRegex)) {
console.log('Incorrect', m);
}
});

会输出

Incorrect <span title=''style="margin:37px;"/>
Incorrect <a title=""gg ff/>
Incorrect <a title="u" hghghgh title="j"example>
Incorrect <a title=""gg ff>

评论更新

<\w+(\s+[\w-]+(="[^"]*"|='[^']*'|=[\w-]+)?)*\s*/?>

关于html - 属性html之间没有空格的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34535190/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com