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?

+3


source to share


4 answers


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"]
      

Run codeHide result


(?![^{]*}

is a negative result that asserts after the number we don't have }

in front before matching{

+2


source


A way of capturing everything you don't need, for example:



var result = txt.replace(/((?:{[^}]*}|[^#{]|#(?!\d))*)(#\d+)/g, '$1 number:$2 '); 

      

+2


source


Yes, use this one: (?!{)#\d(?!})

Demo

+1


source


var str = "nums#1#2#3{#4}#5";
var result=str.match(/#\d+(?!})/g);
console.log(result);
      

Run codeHide result


you can write too.

0


source







All Articles