Eddie Dane
Eddie Dane

Reputation: 1589

Matching patterns not within a set of opening and closing characters e.g {}, ()

I have this string pattern below

str = "nums#1#2#3{#4}#5"

Its there a way I can match all the #\d+ patterns excluding the ones within the curly braces.

I am currently achieving the desired result by replace the curly braces and everything withing them with an empty string before matching.

str = str.replace(/\{[^}]*\}/g, '');
match = str.match(/#\d+/g);

Its there a way to do this in javascript regular expression without the first replacement?

Upvotes: 3

Views: 55

Answers (4)

Mr.lin
Mr.lin

Reputation: 99

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

you can write like this too.

Upvotes: 0

anubhava
anubhava

Reputation: 786261

Assuming { and } 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 lookahead that asserts after a number we don't have a } ahead before matching a {

Upvotes: 2

Stephane Janicaud
Stephane Janicaud

Reputation: 3627

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

Demo

Upvotes: 1

Casimir et Hippolyte
Casimir et Hippolyte

Reputation: 89639

The way is to capture all that you don't want before, example:

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

Upvotes: 2

Related Questions