vendredi 9 octobre 2015

I solved a regexp issue associated with IE9, but I'm not sure how or why it works

Background

I have recently had a problem with a regular expression not working as expected in IE9. I tracked the issue down to a specific block inside the expression, namely [^].

var reg = /((?:abc.[^]*?)?test\s*(?:xyz)?\s*)[^]*?/;

The problem

var str = 'abc 123\nabc 123\nabc 123\ntest xyz';
var reg = /((?:abc.[^]*?)?test\s*(?:xyz)?\s*)[^]*?/;
alert(reg.exec(str));

In other words:

Input:

abc123
abc123
abc123
test xyz

Output

Expected: ["abc 123\nabc 123\nabc 123\ntest xyz","abc 123\nabc 123\nabc 123\ntest xyz"]

Chrome: ["abc 123\nabc 123\nabc 123\ntest xyz","abc 123\nabc 123\nabc 123\ntest xyz"]

IE9: ["test xyz", "test xyz"] // Wrong!!!

Attempted solution

I found that the [^] block is causing the error. By simply switching [^] to [\S\s] I was able to attain the expected output in IE9.

var str = 'abc 123 abc abc test xyz';
var reg = /[\S\s]*?test\s*([\S\s]*)/i;
alert(JSON.stringify(reg.exec(str)));

Output

Expected: ["abc 123\nabc 123\nabc 123\ntest xyz","abc 123\nabc 123\nabc 123\ntest xyz"]

Chrome: ["abc 123\nabc 123\nabc 123\ntest xyz","abc 123\nabc 123\nabc 123\ntest xyz"]

IE9: ["abc 123\nabc 123\nabc 123\ntest xyz","abc 123\nabc 123\nabc 123\ntest xyz"]

Question

So what is the essential difference between [^] and [\S\s]? What is the problem here? Am I just dealing with an edge-case in the IE-javascript engine?




Aucun commentaire:

Enregistrer un commentaire