使用正则表达式验证自定义表达式

Validate Custom expression using Regex

如果我有这样的字符串

${employee} and ${} should be validate

我想获取所有包含

模式的子字符串

${}

并验证以 ${ 和 } 开头的字符串是否必须具有值?

假设以下字符串

  ${employee} and ${} should be validate

它应该 return 有两个元素的数组

[${员工}, ${}]

并且在验证后它应该显示第二个元素无效(因为它是空白的)

为此,我尝试了以下代码

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);

但它不是 return 所需的输出。

伙计们,请提供一些帮助

您可以尝试更改正则表达式

/($)(\{)(.*)(\})/

/($)(\{)[^\}]+(\})/

试试这个:

$\{(\w+)?\}

(\w+)?会考虑${}里面是否有字符

您可以使用以下解决方案:使用 /${[^{}]*}/g 正则表达式和 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>