javascript match()regex函数应返回什么? [英] What should the javascript match() regex function return?

查看:106
本文介绍了javascript match()regex函数应返回什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以这个例子为例:

"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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆