javascript - RegExp: Different results when using Backreference -
see http://jsfiddle.net/aeeun/
why when use backreference vs no backrefences, different results?
var str = "hello world\nhello "; document.write("without backreference: <br />"); var match = str.match(/\s(?![\s\s]*\s)/); document.write("- match.index: " + match.index + "<br />"); // index 16 document.write("with backreference: <br />"); var match = str.match(/(\s)(?![\s\s]*\1)/); document.write("- match.index: " + match.index); // index 6
the difference constrain 2 character same.
in first regular expression there must not any non-whitespace character following:
/\s(?![\s\s]*\s)/
this means match non-whitespace character not followed other non-whitespace character. that’s why matches last o
followed whitespace:
"hello world\nhello " ^ no other non-whitespace character following
but in second regular expression there must not specific character following matched before:
/(\s)(?![\s\s]*\1)/
this means match non-whitespace character not appear again in rest of string. that’s why w
matched it’s first non-whitespace character not appear again after first occurrence:
"hello world\nhello " ^ no other “w” following
that’s why it’s called backreference: reference matched string.
Comments
Post a Comment