yazoox

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

  •  
  •   yazoox · Sep 22, 2021 · 1761 views
    This topic created in 1718 days ago, the information mentioned may be changed or developed.

    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 replies    2021-09-23 11:16:42 +08:00
    gucheen
        1
    gucheen  
       Sep 22, 2021
    (.+){10,}
    ->
    (.{10,})
    wxclover
        2
    wxclover  
       Sep 22, 2021
    name1.match(/^google-(.{10,})-name$/)
    momocraft
        3
    momocraft  
       Sep 22, 2021
    我想知道为什么 name1 name2 原本是可以匹配的

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

    你确定吗?我在 Chrome console 里面试了一下 matches[1] 是 "1"(最后一个字符),这应该是对的,你怎么能拿到整个数字字符串的
    coolan
        6
    coolan  
       Sep 22, 2021 via Android
    chrome console 测试按这个写法,matches1[1]:1,matches2[1]:s,我好奇你第一个手机号怎么取出来的?
    yazoox
        7
    yazoox  
    OP
       Sep 23, 2021
    @gucheen
    it works. 万分感谢
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   2583 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 35ms · UTC 11:02 · PVG 19:02 · LAX 04:02 · JFK 07:02
    ♥ Do have faith in what you're doing.