javascript match()regex函数应返回什么? [英] What should the javascript match() regex function return?
问题描述
以这个例子为例:
"12345".match(/(?=(\d{4}))/g);
将上面的行粘贴到我的(Chrome)控制台中将为我返回["", ""]
,但是我正在尝试提取["1234", "2345"]
的数组. 此MDN文章似乎表明我确实应该期望有一组匹配项.
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.
推荐答案
It seems regular expressions are not the right tool for the job, as explained by trincot above.
尝试赎回自己,这是一个有趣的解决方案,涉及数组和slice
.文字4
可以替代任何其他数字来达到类似的效果.
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)
)
这篇关于javascript match()regex函数应返回什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!