0

This code detects if a regular expression is in a string, and returns them as a JSON string

According to the code, the code does not support for any regex starting with special characters such as (#,@..etc). If i call the function js_regex(#3[0-9]{2},"#312 hyderabad") , #312 is not getting returned as a rslt, whereas if I call js_regex(3[0-9]{2},"312 hyderabad") , 312 is getting returned as rslt

How do I support the patterns for special characters also in the below code?

function js_regex(expr, str) {
  var rslt = "";

  // extract any specific flags
  var flags = "gi";
  if (expr.startsWith("/")) {
    var exprend = expr.length - 1;
    if (!expr.endsWith("/")) {
      exprend = expr.lastIndexOf("/");
      flags = expr.substring(exprend + 1);
    }
    expr = expr.substring(1, exprend);
  }
  if (expr.length === 0) {
    return rslt;
  }

  // only interested in words
  expr = "\\b" + expr + "\\b";

  // run the regex, and save the results as a JSON string
  var re = new RegExp(expr, flags);
  var matches = str.match(re);
  if (matches) {
    rslt = JSON.stringify(matches);
  }
  return rslt;
};

console.log(js_regex("#3[0-9]{2}", "#312 hyderabad"))
console.log(js_regex("3[0-9]{2}", "312 hyderabad"))

3
  • I made you a snippet Commented Apr 8, 2020 at 8:53
  • 2
    It is a usual, frequent issue. expr = "\\b" + expr + "\\b"; must be something like expr = "(?:^|\\W)(" + expr.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&') + ")(?!\\w)"; var matches =[]; and then use while(m=re.exec(str)) { matches.push(m[1]); } Commented Apr 8, 2020 at 8:56
  • See stackoverflow.com/a/32376884/3832970 Commented Apr 8, 2020 at 9:01

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.