Skip to content

Instantly share code, notes, and snippets.

@slevithan
Created April 14, 2012 20:48
Show Gist options
  • Save slevithan/2387815 to your computer and use it in GitHub Desktop.
Save slevithan/2387815 to your computer and use it in GitHub Desktop.
Simulating lookbehind in JavaScript
// Simulating infinite-length leading lookbehind in JavaScript. Uses XRegExp
// and XRegExp.matchRecursive. Any regex pattern can be used within lookbehind,
// including nested groups. Captures within lookbehind are not included in
// match results. Lazy repetition in lookbehind may lead to unexpected results.
(function (XRegExp) {
function preparePattern(pattern, flags) {
var lbOpen, lbEndPos, lbInner;
flags = flags || "";
// Extract flags from a leading mode modifier, if present
pattern = pattern.replace(/^\(\?([\w$]+)\)/, function ($0, $1) {
flags += $1;
return "";
});
if (lbOpen = /^\(\?<([=!])/.exec(pattern)) {
// Extract the lookbehind pattern. Allows nested groups, escaped parens, and unescaped parens within classes
lbEndPos = XRegExp.matchRecursive(pattern, /\((?:[^()[\\]|\\.|\[(?:[^\\\]]|\\.)*])*/.source, "\\)", "s", {
valueNames: [null, null, null, "right"],
escapeChar: "\\"
})[0].end;
lbInner = pattern.slice("(?<=".length, lbEndPos - 1);
} else {
throw new Error("lookbehind not at start of pattern");
}
return {
lb: XRegExp("(?:" + lbInner + ")$(?!\\s)", flags.replace(/[gy]/g, "")), // $(?!\s) allows use of flag m
lbType: lbOpen[1] === "=", // Positive or negative lookbehind
main: XRegExp(pattern.slice(("(?<=)" + lbInner).length), flags)
};
}
XRegExp.execLb = function (str, pattern, flags) {
var pos = 0, match, leftContext;
pattern = preparePattern(pattern, flags);
while (match = XRegExp.exec(str, pattern.main, pos)) {
leftContext = str.slice(0, match.index);
if (pattern.lbType === pattern.lb.test(leftContext)) {
return match;
}
pos = match.index + 1;
}
return null;
};
XRegExp.testLb = function (str, pattern, flags) {
return !!XRegExp.execLb(str, pattern, flags);
};
XRegExp.searchLb = function (str, pattern, flags) {
var match = XRegExp.execLb(str, pattern, flags);
return match ? match.index : -1;
};
XRegExp.matchAllLb = function (str, pattern, flags) {
var matches = [], pos = 0, match, leftContext;
pattern = preparePattern(pattern, flags);
while (match = XRegExp.exec(str, pattern.main, pos)) {
leftContext = str.slice(0, match.index);
if (pattern.lbType === pattern.lb.test(leftContext)) {
matches.push(match[0]);
pos = match.index + (match[0].length || 1);
} else {
pos = match.index + 1;
}
}
return matches;
};
XRegExp.replaceLb = function (str, pattern, replacement, flags) {
var output = "", pos = 0, lastEnd = 0, match, leftContext;
pattern = preparePattern(pattern, flags);
while (match = XRegExp.exec(str, pattern.main, pos)) {
leftContext = str.slice(0, match.index);
if (pattern.lbType === pattern.lb.test(leftContext)) {
// Doesn't work correctly if lookahead in regex looks outside of the match
output += str.slice(lastEnd, match.index) + XRegExp.replace(match[0], pattern.main, replacement);
lastEnd = match.index + match[0].length;
if (!pattern.main.global) {
break;
}
pos = match.index + (match[0].length || 1);
} else {
pos = match.index + 1;
}
}
return output + str.slice(lastEnd);
};
}(XRegExp));
// Test it...
console.log(XRegExp.execLb("Fluffy cat", "(?<=fluffy\\W+)(?<first>c)at", "i"));
// -> ["cat", "c"]
// Result has named backref: result.first -> "c"
console.log(XRegExp.execLb("Fluffy cat", "(?<!fluffy\\W+)cat", "i"));
// -> null
console.log(XRegExp.testLb("Fluffy cat", "(?<=fluffy\\W+)cat", "i"));
// -> true
console.log(XRegExp.testLb("Fluffy cat", "(?<!fluffy\\W+)cat", "i"));
// -> false
console.log(XRegExp.searchLb("Catwoman's fluffy cat", "(?<=fluffy\\W+)cat", "i"));
// -> 18
console.log(XRegExp.searchLb("Catwoman's fluffy cat", "(?<!fluffy\\W+)cat", "i"));
// -> 0
console.log(XRegExp.matchAllLb("Catwoman's cats are fluffy cats", "(?<=fluffy\\W+)cat\\w*", "i"));
// -> ["cats"]
console.log(XRegExp.matchAllLb("Catwoman's cats are fluffy cats", "(?<!fluffy\\W+)cat\\w*", "i"));
// -> ["Catwoman", "cats"]
console.log(XRegExp.replaceLb("Catwoman's fluffy cat is a cat", "(?<=fluffy\\W+)cat", "dog", "ig"));
// -> "Catwoman's fluffy dog is a cat"
console.log(XRegExp.replaceLb("Catwoman's fluffy cat is a cat", "(?<!fluffy\\W+)cat", "dog", "ig"));
// -> "dogwoman's fluffy cat is a dog"
console.log(XRegExp.replaceLb("Catwoman's fluffy cat is a cat", "(?<!fluffy\\W+)cat", function ($0) {
var first = $0.charAt(0);
return first === first.toUpperCase() ? "Dog" : "dog";
}, "ig"));
// -> "Dogwoman's fluffy cat is a dog"
@slevithan
Copy link
Author

I've also posted an alternate version that splits the lookbehind and the main pattern into separate arguments, and does not require the XRegExp.matchRecursive addon.

This code is released under the MIT License.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment