1

I have a variable,

var inp = "B123213";

Now when i apply the below regex,

var rg = /\d+/;

and perform String match operation,

console.log(inp.match(rg));

I get the output as 123213, denoting that the expression is greedy. But when i use *, instead of +, the expression does not return a match. Please help me understand why an empty match is returned. Shouldn't it too be returning the same result.

Since the doc says about ?,

If used immediately after any of the quantifiers *, +, ?, or {}, makes the quantifier non-greedy (matching the fewest possible characters), as opposed to the default, which is greedy (matching as many characters as possible). For example, applying /\d+/ to "123abc" matches "123". But applying /\d+?/ to that same string matches only the "1".

I would expect an empty match only on applying /\d*?/.

BatScream
  • 19,260
  • 4
  • 52
  • 68
  • 2
    an awesome site for learning and playing with regex is http://regex101.com/ I has helped me out greatly learning and playing with regular expressions. – Sten Muchow Oct 29 '14 at 18:44

2 Answers2

4

Change your string to 123213 and it will match all the digits.

The engine won't advance unless it has to.

Here it sees a B123213 and it can match nothing ie \d* at that position,
so it does.

So, its really about position first, quantifiers second.

3

when * is used it returns three matches.One empty and second the same as one returned by +.The empty is due to the fact that when string is consumed \d* can match the empty string at the end and at start as well.You are getting the first match.Make it a group to see all matches.

see demo.

http://regex101.com/r/gT6kI4/2

vks
  • 67,027
  • 10
  • 91
  • 124