Reputation: 1589
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
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
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
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