JS 里面的 string.match,怎么把匹配字符串取出来?

2021-09-22 16:52:34 +08:00
 yazoox

typescript

const regKey: string = /^google-(.+){10,}-name$/;
const name1: string = "google-15922231201-name";
const name2: string = "google-dbid%3AAACd8VcY240_OYIPqr4L-8M6RvNEDErLG1s-name";

const matches1 = name1.match(regKey);
const matches2 = name2.match(regKey);

在这里,matches1[1],是能够拿到 "15922231201",但是,matches2[1],却拿不到中间的那一长串字符串。返回值是 "s",只有一个 s......

我在 https://regex101.com/ 这里试过,引擎选 javascript,这两字符串,都是符合要求的。

请问一下,这里的 reg 哪里写的不对。

另,我知道可以直接用 substring + 长度,直接拿到 google- & -name 匹配的中间的字符串,但这里,我想了解下,这个正则是哪里写得不对了?

862 次点击
所在节点    正则表达式
7 条回复
gucheen
2021-09-22 17:00:17 +08:00
(.+){10,}
->
(.{10,})
wxclover
2021-09-22 17:07:43 +08:00
name1.match(/^google-(.{10,})-name$/)
momocraft
2021-09-22 17:12:45 +08:00
我想知道为什么 name1 name2 原本是可以匹配的

(.+){10,} 不是应该匹配到一个 (括号里的东西重复至少 10 次) 的串吗? name1 name2 里都没有满足这个的
momocraft
2021-09-22 17:27:27 +08:00
regex101 的提示: A repeated capturing group will only capture the last iteration. Put a capturing group around the repeated group to capture all iterations or use a non-capturing group instead if you're not interested in the data

从这个提示看, 每个 iteration 可以不同, 只有最后一个匹配到了 s, 这样就和代码行为一致
JeffGe
2021-09-22 17:33:40 +08:00

你确定吗?我在 Chrome console 里面试了一下 matches[1] 是 "1"(最后一个字符),这应该是对的,你怎么能拿到整个数字字符串的
coolan
2021-09-22 17:41:15 +08:00
chrome console 测试按这个写法,matches1[1]:1,matches2[1]:s,我好奇你第一个手机号怎么取出来的?
yazoox
2021-09-23 11:16:42 +08:00
@gucheen
it works. 万分感谢

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/803424

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX