Matching patterns are not part of the open and close character set, for example {}, ()
I have this line pattern below
str = "nums#1#2#3{#4}#5"
In this case, I can match all patterns #\d+
except those in curly braces.
Currently I am achieving my desired result by replacing curly braces and everything by using an empty string in front of them.
str = str.replace(/\{[^}]*\}/g, '');
match = str.match(/#\d+/g);
Is there a way to do this in a javascript regex without the first replacement?
source to share
Assuming {
both are }
balanced, you can use this negative lookahead to match numbers not within {...}
:
var str = "nums#1#2#3{#4}#5";
var arr = str.match(/#\d+(?![^{]*})/g)
console.log(arr)
//=> ["#1", "#2", "#3", "#5"]
(?![^{]*}
is a negative result that asserts after the number we don't have }
in front before matching{
source to share
var str = "nums#1#2#3{#4}#5";
var result=str.match(/#\d+(?!})/g);
console.log(result);
you can write too.
source to share