-1

Take this example:

"12345".match(/(?=(\d{4}))/g);

Pasting that line above into my (Chrome) console is returning ["", ""] for me but I am trying to extract an array of ["1234", "2345"]. This MDN article seems to indicate that I should, indeed, expect an array of matches.

The particular regex on this exact string definitely returns those matches as proven in this question from yesterday.

Can anyone please clarify what the expected behavior should be and any alternative approaches I could take here if I have made an incorrect assumption about this function and/or am misusing it.

Community
  • 1
  • 1
DaveHolt
  • 119
  • 1
  • 3
  • 13
  • 3
    (1) You cannot match the same character in your source string in multiple matches, which apparently is what you want, since "234" is in both desired matches. (2) A look-ahead is not capturing the characters it is looking ahead to, so that is why you get empty strings. – trincot Feb 25 '17 at 12:48
  • You can't just steal a regex from an answer but ignore the code that uses the regex. Chrome produces the expected output for your code. If you use the code provided in the answer you linked, you'll get the result you want. – Aran-Fey Feb 25 '17 at 12:52
  • @Rawing - As I said in a comment there, the code resulted in an infinite loop for me. I will revisit it later today but `match()` appealed to me more as it seems shorter/more readable. – DaveHolt Feb 25 '17 at 12:56
  • Please specify what _you_ expect from _your_ string. – try-catch-finally Feb 25 '17 at 12:58

2 Answers2

0

Edit: It seems regular expressions are not the right tool for the job, as explained by trincot above.

In an attempt to redeem myself, here is a fun solution involving arrays and slice. The literal 4 can be substituted for any other number to achieve a similar effect.

console.log(
  '12345'.split('').map((_, i, a) => a.slice(i, i + 4).join('')).slice(0, 1 - 4)
)
gyre
  • 16,369
  • 3
  • 37
  • 47
0

You cited the question Match all consecutive numbers of length n. Why not take the code from the accepted answer there (https://stackoverflow.com/a/42443329/4875869)?

What goes wrong with "12345".match(/(?=(\d{4}))/g); is that in ["", ""] the first "" corresponds to the match with $0 (the whole match) = "", $1 (group 1) = "1234", and so for the second "" (the array is like [$0 (match 1), $0 (match 2)] because of g).

If you omit the g ("12345".match(/(?=(\d{4}))/);), you'll get ["", "1234"] ([$0 (the match), $1 (the match)]).

Community
  • 1
  • 1
Kirill Bulygin
  • 3,658
  • 1
  • 17
  • 23