Skip to content

Instantly share code, notes, and snippets.

@zestime
Last active August 29, 2015 14:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zestime/773c662407bfb24d1430 to your computer and use it in GitHub Desktop.
Save zestime/773c662407bfb24d1430 to your computer and use it in GitHub Desktop.
> /(aaa)bbb/.exec("aaabbbccc") // lookbehind?
["aaabbb", "aaa"]
> /([^a]{3})bbb/.exec("dddbbbeee") // negative lookbehind?
["dddbbb", "ddd"]
// Negative lookbehind regex in Javascript
// http://stackoverflow.com/questions/641407/javascript-negative-lookbehind-equivalent?answertab=votes#answer-641432
newString = string.replace(/([abcdefg])?m/, function($0,$1){ return $1?$0:'m';});
// examples of lookbehind
"Lookahead".replace(/(Look?)ahead/, function($0,$1){ return $1?$1+"behind":$0;})
> Lookbehind
"Lookahead".replace(/(See?)ahead/, function($0,$1){ return $1?$1+"behind":$0;})
> Lookahead
"Lookahead".replace(/([^Look])?ahead/, function($0,$1){ return $1?$0:'behind';})
> Lookbehind
String.prototype.lookbehind = function(p) {
var s = new RegExp(p.replace(/\(\?<([=!])(.+)\)(.+)/,function($0,$1,$2,$3){return ($1=="!"?"[^"+$2+"]":$2)+"(" + $3 + ")";})).exec(this);
return s?(s[1]?s[1]:s[0]):null;
};
"123".lookbehind("(?<=1)2");
> 2
"123".lookbehind("(?<!1)2");
> null
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment