[英]Regex parsing in javascript
你能帮助我解析我尝试了很多但无法做到的正则表达式吗?
输入: <a onclick="javascript:collapse('displayText','hideText','whyInfo-arrow-image')"><span sd:text="${whyInfoLabel}">Learn more about Authentication</span> <img id="whyInfo-arrow-image" sd:src="${downwardArrowImage}" height="20" width="20" >
预期: sd:text="${whyInfoLabel}"
和sd:src="${downwardArrowImage}"
我的尝试 1 : "/\\$\\{(\\w*)\\}/g"
它只能选择{whyInfoLabel}
& {downwardArrowImage}
我的尝试 2 : "/sd.*\\$\\{(\\w*)\\}/g"
这无法拆分。
我对 Regex 和 JavaScript 很陌生。
任何帮助都会很棒。
你在JS,为什么不使用DOM来解析HTML呢? 正则表达式并非旨在解析 HTML,但 DOM 提供了专门为此目的而设计的实用程序。
如果您的浏览器支持它,您应该考虑使用DOMParser来执行此操作:
var html = "<a onclick=\"javascript:collapse('displayText','hideText','whyInfo-arrow-image')\"><span sd:text=\"${whyInfoLabel}\">Learn more about Authentication</span> <img id=\"whyInfo-arrow-image\" sd:src=\"${downwardArrowImage}\" height=\"20\" width=\"20\" >";
var parser = new DOMParser();
var doc = parser.parseFromString(html, "text/html");
var attrText = doc.querySelector('span').getAttribute("sd:text");
console.log(attrText);
var attrSrc = doc.querySelector('img').getAttribute("sd:src");
console.log(attrSrc);
“${whyInfoLabel}”
“${downwardArrowImage}”
试试这个:/( /(sd:.*=".*")/Ug
:. /(sd:.*=".*")/Ug
或者这样: /\\{(.*)\\}/Ug
这应该给你一个数组中的两个结果:
/sd:(?:text|src)=\"[^\"]*"/g
正则表达式匹配 'sd:' 开头,然后是 'text' 或 'src'、等号、双引号后跟零个或多个不是双引号的字符,最后是双引号。
只需调用(假设您的文本位于名为'text'
的变量中:
var regex =/sd:(?:text|src)=\"[^\"]*"/g;
var matches = text.match(regex);
var match0 = matches[0];
var match1 = matches[1];
你可以试试这个正则表达式。 希望这可以帮助。
const regex = /\\w+:\\w+="\\$\\{\\w*\\}"/g; const input = '<a onclick="javascript:collapse(' + 'displayText' + ',' + 'hideText' + ','+ 'whyInfo-arrow-image' + ')"><span sd:text="${whyInfoLabel}">Learn more about Authentication</span> <img id="whyInfo-arrow-image" sd:src="${downwardArrowImage}" height="20" width="20" >'; console.log(input.match(regex))
asdf = new RegExp('(sd:.+?[}])+', 'gi');
console.log(str.match(asdf));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.