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);
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.
?= 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).
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'));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With