Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

正则多次匹配无效的问题 #85

Open
XXHolic opened this issue Jun 13, 2020 · 0 comments
Open

正则多次匹配无效的问题 #85

XXHolic opened this issue Jun 13, 2020 · 0 comments

Comments

@XXHolic
Copy link
Owner

XXHolic commented Jun 13, 2020

引子

检测一批手机号码是否都符合要求的格式,循环用正则校验,发现无效。去查找了下资料,发现了之前没有注意到地方。

问题

下面是问题重现:

const arr=['18311112222','18344445555','2857898098']
const reg = /^1[3-9]\d{9}$/g;
const result = arr.find(ele => !reg.test(ele));
console.info({result});

// {result: "18344445555"}

按照上面的正则,第二个号码符合要求,却返回了 false ,去查了资料,发现:

如果正则表达式设置了全局标志 gtest() 的执行会改变正则表达式 lastIndex 属性。连续的执行 test() 方法,后续的执行将会从 lastIndex 处开始匹配字符串。

验证一下:

const arr=['18311112222','18344445555','2857898098']
const reg = /^1[3-9]\d{9}$/g;
const result = arr.find(ele => {
  const lastIndex = reg.lastIndex;
  console.info({lastIndex});
  return !reg.test(ele);
});

// {lastIndex: 0}
// {lastIndex: 11}

解决方法

方法 1

去掉全局标志 g ,再想一想这个场景下没有必要使用全局匹配。

方法 2

使用 String.prototype.search()

const arr=['18311112222','18344445555','2857898098']
const reg = /^1[3-9]\d{9}$/g;
const result = arr.find(ele => ele.search(reg) === -1);

方法 3

每次循环匹配的时候,重新声明一个正则。

const arr=['18311112222','18344445555','2857898098']
const result = arr.find(ele => {
  const reg = /^1[3-9]\d{9}$/g;
  return !reg.test(ele);
});

参考资料

🗑️

最近脑海里面一直浮现“乐园追放”这个词,就去搜了一下,一看封面好像是机甲类的作品,就感觉没什么兴趣。但为了解决一下心中的疑惑,就去看了一下。

结果发现虽然有机甲,但机甲最精彩的打斗在最后出现,整体也不多。讲的故事大都对虚拟世界、AI、人类三方面进行不同角度的探讨,个人感觉还是蛮有意思。

74-poster

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant