如果我有一个像
${employee} and ${} should be validate
我想获取包含该模式的所有子字符串,例如
${}
并验证以$ {和}开头的字符串是否必须具有值?
假设下面的字符串
${employee} and ${} should be validate
它应该返回带有两个元素的数组
[$ {employee},$ {}]
并在验证后应将第二个元素显示为无效(因为它为空白)
为此,我尝试了以下代码
function fetchMatches(theString, theRegex){
return theString.match(theRegex).map(function(el) {
var index = theString.indexOf(el);
return [index, index + el.length - 1];
});
}
fetchMatches(" ${employee} and ${} should be validate",/(\$)(\{)(.*)(\})/i);
但它没有返回所需的输出。
伙计们,请提出一些帮助
您可以使用以下解决方案:使用/\${[^{}]*}/g
regex与String#match
来获取所有匹配项,然后遍历匹配项以检查哪些匹配项具有空值:
var s = "${user.lastName}${user.firstName}${}";
var m, results = [];
var re = /\${[^{}]*}/g;
while ((m=re.exec(s)) !== null) {
if (m[0] === "${}") {
console.log("Variable at Index",m.index,"is empty.");
} else {
results.push(m[0]);
}
}
console.log(results);
既然您提到了可以嵌套的值,则可以使用XRegExp
:
var s = "${user.${}lastName}${user.firstName}${}";
var res = XRegExp.matchRecursive(s, '\\${', '}', 'g', {
valueNames: [null, null, 'match', null]
});
for (var i=0; i<res.length; i++) {
if (~res[i]["value"].indexOf("${}") || res[i]["value"] == "") {
console.log("The",res[i]["value"],"at Index",res[i]["start"],"is invalid.");
} else {
console.log("The",res[i]["value"],"at Index",res[i]["start"],"is valid.");
}
}
<script src="http://cdnjs.cloudflare.com/ajax/libs/xregexp/3.1.1/xregexp-all.min.js"></script>
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句