Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular Expression Guidance needed for Javascript

In the following input string:

{$foo}foo bar \\{$blah1}oh{$blah2} even more{$blah3} but not{$blarg}{$why_not_me}

I am trying to match all instances of {$SOMETHING_HERE} that are not preceded by an unescaped backslash.

Example:

I want it to match {$SOMETHING} but not \{$SOMETHING}.

But I do want it to match \\{$SOMETHING}

Attempts:

All of my attempts so far will match what I want except for tags right next to each other like {$SOMETHING}{$SOMETHING_ELSE}

Here is what I currently have:

var input = '{$foo}foo bar \\{$blah1}oh{$blah2} even more{$blah3} but not{$blarg}{$why_not_me}';
var results = input.match(/(?:[^\\]|^)\{\$[a-zA-Z_][a-zA-Z0-9_]*\}/g);
console.log(results);

Which outputs:

["{$foo}", "h{$blah2}", "e{$blah3}", "t{$blarg}"]

Goal

I want it to be :

["{$foo}", "{$blah2}", "{$blah3}", "{$blarg}", "{$why_not_me}"]

Question

Can anybody point me in the right direction?

like image 291
nathanjosiah Avatar asked Nov 04 '22 02:11

nathanjosiah


1 Answers

The problem here is that you need a lookbehind, which JavaScript Regexs don't support

basically you need "${whatever} if it is preceded by a double slash but not a single slash" which is what the lookbehind does.

You can mimic simple cases of lookbehinds, but not sure if it will help in this example. Give it a go: http://blog.stevenlevithan.com/archives/mimic-lookbehind-javascript

edit Btw, I don't think you can do this a 'stupid way' either because if you have [^\\]\{ you'll match any character that is not a backslash before the brace. You really need the lookbehind to do this cleanly.

Otherwise you can do

(\\*{\$[a-zA-Z_][a-zA-Z0-9_]*\})

Then just count the number of backslashes in the resulting tokens.

like image 61
Griffin Avatar answered Nov 09 '22 14:11

Griffin