V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
yazoox
V2EX  ›  正则表达式

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

  •  
  •   yazoox · 2021-09-22 16:52:34 +08:00 · 835 次点击
    这是一个创建于 918 天前的主题,其中的信息可能已经有所发展或是发生改变。

    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 匹配的中间的字符串,但这里,我想了解下,这个正则是哪里写得不对了?

    7 条回复    2021-09-23 11:16:42 +08:00
    gucheen
        1
    gucheen  
       2021-09-22 17:00:17 +08:00
    (.+){10,}
    ->
    (.{10,})
    wxclover
        2
    wxclover  
       2021-09-22 17:07:43 +08:00
    name1.match(/^google-(.{10,})-name$/)
    momocraft
        3
    momocraft  
       2021-09-22 17:12:45 +08:00
    我想知道为什么 name1 name2 原本是可以匹配的

    (.+){10,} 不是应该匹配到一个 (括号里的东西重复至少 10 次) 的串吗? name1 name2 里都没有满足这个的
    momocraft
        4
    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
        5
    JeffGe  
       2021-09-22 17:33:40 +08:00

    你确定吗?我在 Chrome console 里面试了一下 matches[1] 是 "1"(最后一个字符),这应该是对的,你怎么能拿到整个数字字符串的
    coolan
        6
    coolan  
       2021-09-22 17:41:15 +08:00 via Android
    chrome console 测试按这个写法,matches1[1]:1,matches2[1]:s,我好奇你第一个手机号怎么取出来的?
    yazoox
        7
    yazoox  
    OP
       2021-09-23 11:16:42 +08:00
    @gucheen
    it works. 万分感谢
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3913 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 05:10 · PVG 13:10 · LAX 22:10 · JFK 01:10
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.