繁体   English   中英

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

[英]Validate Custom expression using Regex

如果我有一个像

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

但它没有返回所需的输出。

伙计们,请提出一些帮助

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

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

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

试试这个:

\$\{(\w+)?\}

(\\w+)? 将考虑模式$$中是否有字符

您可以使用以下解决方案:使用带有String#match /\\${[^{}]*}/g regex来获取所有匹配项,然后遍历匹配项以检查其中是否有空值:

 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> 

暂无
暂无

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

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