简体   繁体   English

用于匹配HTML字符串中的属性的javascript正则表达式

[英]javascript regex for matching attributes in HTML string

Can anyone look at my regex in javascript and suggest a correct one? 任何人都可以在javascript中查看我的正则表达式并提出正确的建议吗?

I'm trying to select attributes(name/value) pairs in an HTML/XML string like following? 我正在尝试在HTML / XML字符串中选择属性(名称/值)对,如下所示?

<unknowncustom:tag attrib1="XX' XX'" attrib2='YY" YY"' attrib3=ZZ""'>/unknowncustom:tag>

SOME TEXT that is not part of any tag and should not be selected, name='XX', y='ee';

<custom:tag attrib1="XX' XX'" attrib2='YY" YY"' attrib3=ZZ""'>/custom:tag>

I found many solutions but none seem foolproof (including this one Regular expression for extracting tag attributes ) 我找到了很多解决方案但没有一个看起来万无一失(包括这个用于提取标签属性的正则表达式

My current regex selects the first attribute pair but can't figure out how to make it select all matching attributes. 我当前的正则表达式选择第一个属性对但无法弄清楚如何使其选择所有匹配的属性。 Here is the regex: 这是正则表达式:

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

Thanks 谢谢

Let's have a go: 我们来吧:

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

Regex is not ideal for this. 正则表达式并不理想。 If your attributes contain unescaped angle brackets < > it probably will not work. 如果您的属性包含未转义的尖括号< >它可能无效。

Proof: http://regex101.com/r/dD4uT4 证明: http//regex101.com/r/dD4uT4

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM