Ivan Akulov
Ivan Akulov

Reputation: 4323

Dash in regular expression

According to the documentation, String.prototype.match() must return all matches of a regular expression in a string. However,

"Foo 09:00 bar 21-00 foobar".match(/\d{2}[:\-]\d{2}/)

returns only ["09:00"], whereas the expected result is ["09:00", "21:00"]. Why?

By the way,

"Foo 09:00 bar 21-00 foobar".split(/\d{2}[:\-]\d{2}/)

returns ["Foo ", " bar ", " foobar"], which means 21-00 is matched by the regular expression.

Upvotes: 0

Views: 78

Answers (2)

Amit Joki
Amit Joki

Reputation: 59232

You are missing g (global) modifier. Use it.

If you don't, it will stop at the first match.

Like this:

"Foo 09:00 bar 21-00 foobar".match(/\d{2}[:-]\d{2}/g)

Also, you don't need to escape - if it is at the starting or at the end of character class.

The MDN document which you referred also says:

  1. returns the same result as RegExp.exec(str) [i.e. the captured groups, index, etc] if the regular expression does not include the g flag
  2. returns an Array containing all matches if the regular expression includes the g flag

Upvotes: 5

Bergi
Bergi

Reputation: 664513

According to the documentation, String.prototype.match()

  • returns the same result as RegExp.exec(str) [i.e. the captured groups, index, etc] if the regular expression does not include the g flag
  • returns an Array containing all matches if the regular expression includes the g flag
> "Foo 09:00 bar 21-00 foobar".match(/\d{2}[:\-]\d{2}/)
Array ["09:00", index:4, input:"Foo 09:00 bar 21-00 foobar"]
> "Foo 09:00 bar 21-00 foobar".match(/\d{2}[:\-]\d{2}/g)
Array ["09:00", "21-00"]

Upvotes: 3

Related Questions