ehsan ehsan - 1 year ago 55
Javascript Question

what is difference between these two syntax in my code

What is difference between The following syntaxs in regular expression?

Please give an example.




Answer Source

The first one is just an assertion, a positive look-ahead saying "there must be zero or more characters followed by a digit." If you match it against a string containing at least one digit, it will tell you whether the assertion is true, but the matched text will just be an empty string.

The second one searches for a match, with an assertion (a positive-lookahead) after the match saying "there must be a digit." The matched text will be the characters before the last digit in the string (including any previous digits, because .* is greedy, so it'll consume digits up until the last one, because the last one is required by the assertion).

Note the difference in the match object results:

var str = "foo42";
test("rex1", /(?=.*\d)/, str);
test("rex2", /.*(?=\d)/, str);

function test(label, rex, str) {
  console.log(label, "test result:", rex.test(str));
  console.log(label, "match object:", rex.exec(str));

Output (for those who can't run snippets):

rex1 test result: true
rex1 match object: [
rex2 test result: true
rex2 match object: [

Notice how the match result in the second case was foo4 (from the string foo42), but blank in the first case.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download