PDA

View Full Version : Regex Puzzle



Twey
12-10-2005, 01:43 PM
I have a slight problem. I have a string, in which I want to match /\\e\[([^m]+)m/g, and replace it with a value pulled out of an array, the index of which should be \1. Is this even possible? The problem is that String.replace() doesn't parse \# until it's actually called, and the value needs to be taken from the array before the call happens. For this reason I don't think it can be done. Can anyone suggest an alternative approach?

mwinter
12-10-2005, 05:24 PM
I have a string, in which I want to match /\\e\[([^m]+)m/g, and replace it with a value pulled out of an array, the index of which should be \1.Just to clarify, Twey, you have a string that may contain one or more sequences in a string that would match \e[XXm where XX is a number[1], and you want to replace that entire sequence with the value from the array with the aforementioned numeric index?


Is this even possible?Yes. :)


The problem is that String.replace() doesn't parse \# until it's actually called, and the value needs to be taken from the array before the call happens. When using a string for the second argument, yes. It's simple, though, using a function argument:



string.replace(/\\e\[([^m]+)m/g, function(match, index) {
return array[index];
});
Unfortunately, some browsers (such as IE5) won't support this, so you might need to take a completely different approach:



var pattern = /\\e\[([^m]+)m/g,
result = '',
index = 0,
matches;

while((matches = pattern.exec(string))) {
result += string.substring(index, matches.index)
+ array[matches[1]];
index = pattern.lastIndex;
}
result += string.substring(index);
Mike


[1] I assume it's a number, otherwise an array is inappropriate and an object (literal) would be better (and might do anyway). Moreover, if it is a number, then [^m] could be replaced with \d.

Twey
12-10-2005, 05:35 PM
Aha! Brilliance. Thank you, Mike, that was exactly what I was after :)