问题
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.
回答1:
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)]
).
回答2:
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)
)
来源:https://stackoverflow.com/questions/42456201/what-should-the-javascript-match-regex-function-return