Validate Custom expression using Regex

137 views Asked by At

If I have a string like

${employee} and ${} should be validate

And I want to fetch all substring that contains the pattern like

${}

and validate as if string starting with ${ and } must have value?

suppose for below string

  ${employee} and ${} should be validate

it should return array with two element

[ ${employee}, ${} ]

and upon validate it should show the second element as invalid (as it is blank)

for this, I have tried the following code

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

but it is not returning the desired output.

guys, please suggest some help

3

There are 3 answers

6
Wiktor Stribiżew On BEST ANSWER

You may use the following solution: use /\${[^{}]*}/g regex with String#match to fetch all the matches, and then loop over the matches to check which have an empty value:

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

Since you mentioned that there can be nested values you may use 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>

0
lpg On

You can try changing the regex from

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

to

/(\$)(\{)[^\}]+(\})/
1
Carlos Crespo On

Try this one:

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

(\w+)? will consider the pattern whether there is character inside ${} or not