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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With