Regular Expression Needed for Javascript

In the next line of input:

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

I am trying to match all instances {$SOMETHING_HERE}that are not preceded by a backslash without a return.

Example:

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

But I want it to fit \\{$SOMETHING}

Attempts:

All my attempts so far will match what I want, except for the tags next to each other, for example {$SOMETHING}{$SOMETHING_ELSE}

Here is what I have now:

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);

What outputs:

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

purpose

I want this to be:

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

Question

Can someone point me in the right direction?

+5
source share
3 answers

The problem here is that you need lookbehind which JavaScript Regexs do not support

"$ {whatever}, , ", lookbehind.

lookbehinds, , . : http://blog.stevenlevithan.com/archives/mimic-lookbehind-javascript

, , "", , [^\\]\{, , . , .

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

.

+1

, , / .

: / . \{< * > }

, , .

var input = '{$foo}foo bar \\{$blah1}oh{$blah2} even more\\\\{$blah3} but not{$blarg}{$why_not_me}';

input.split(/(?:[^\\])\\\{[^\}]*\}/).join('').replace(/\}[^\{]*\{/g,'},{').split(/,/));
+1

This is similar to what I want:

var input = '{$foo}foo bar \\{$blah1}oh{$blah2} even more\\\\{$blah3} but not{$blarg}{$why_not_me}';

var results = [];
input.replace(/(\\*)\{\$[a-z_][a-z0-9_]*\}/g, function($0,$1){
    $0 = $0.replace(/^\\\\/g,'');
    var result = ($0.indexOf('\\') === 0 ? false : $0); 

    if(result) {
        results.push(result);
    }
})

console.log(results);

What gives:

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

All Articles