Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular Expression Total Matches on Instances

My test string contains 4 instances of an open square bracket and a closed square bracket, so I would like the following regular expression to return 4 matches, but it only returns 1.

const test = "sf[[[[asdf]]]]asdf"
const regExp = new RegExp(/^.*\[.*\].*$/, "g");
const matches = test.match(regExp).length;

console.log(matches);
like image 593
Chunky Chunk Avatar asked May 22 '19 17:05

Chunky Chunk


People also ask

How do you find the number of matches in a regular expression?

To count the number of regex matches, call the match() method on the string, passing it the regular expression as a parameter, e.g. (str. match(/[a-z]/g) || []). length . The match method returns an array of the regex matches or null if there are no matches found.

What does ?= Mean in regular expression?

?= is a positive lookahead, a type of zero-width assertion. What it's saying is that the captured match must be followed by whatever is within the parentheses but that part isn't captured. Your example means the match needs to be followed by zero or more characters and then a digit (but again that part isn't captured).


1 Answers

You can use a combination of recursion and regular expressions:

function parse(str) {
  const matches = [];

  str.replace(/\[(.*)]/, (match, capture) => {
    matches.push(match, ...parse(capture));
  });

  return matches;
}

console.log(parse('sf[[[[asdf]]]]asdf'));
console.log(parse('st[[as[[asdf]]]a]sdf'));
like image 106
KevBot Avatar answered Oct 14 '22 05:10

KevBot