【问题标题】:RegEx for capturing specific alphanumeric pattern用于捕获特定字母数字模式的正则表达式
【发布时间】:2019-05-22 20:46:39
【问题描述】:

我有这个字符串,我想知道如何提取“10-K_20190304_29_1_20190515”部分。

"nCABALLERO MARIA\r\n10.1-K\r\n10-K_20190304_29_1_20190515\r\n6204 DEPORTES SANTIAGO - PEÑALOLÉN"

我已经试过了,.+(?<=_).+,但它给我带来了更多我需要的角色。

我该如何解决这个问题?

【问题讨论】:

    标签: regex string regex-group regex-greedy uipath


    【解决方案1】:

    在这里,我们喜欢从一个简单的左右边界开始,收集我们想要的数据并将其保存在一个捕获组中($1)。让我们开始吧:

    [0-9]{2}-.+[0-9]{8}
    

    让我们添加我们的捕获组:

    ([0-9]{2}-.+[0-9]{8})
    

    DEMO

    const regex = /[0-9]{2}-.+[0-9]{8}/gm;
    const str = `nCABALLERO MARIA\\r\\n10.1-K\\r\\n10-K_20190304_29_1_20190515\\r\\n6204 DEPORTES SANTIAGO - PEÑALOLÉN`;
    let m;
    
    while ((m = regex.exec(str)) !== null) {
        // This is necessary to avoid infinite loops with zero-width matches
        if (m.index === regex.lastIndex) {
            regex.lastIndex++;
        }
        
        // The result can be accessed through the `m`-variable.
        m.forEach((match, groupIndex) => {
            console.log(`Found match, group ${groupIndex}: ${match}`);
        });
    }

    正则表达式

    如果不需要此表达式,可以在 regex101.com 中修改或更改。

    正则表达式电路

    jex.im 可视化正则表达式:


    如果我们希望添加更多边界,我们当然可以这样做,具体取决于我们可能的输入可能是什么样子。例如,这个表达式有更多的边界:

    ([0-9]{2}-[A-Z]+_[0-9]{8}[0-9_]+.+?[0-9]{8})
    

    DEMO

    const regex = /([0-9]{2}-[A-Z]+_[0-9]{8}[0-9_]+.+?[0-9]{8})/gm;
    const str = `nCABALLERO MARIA\\r\\n10.1-K\\r\\n10-K_20190304_29_1_20190515\\r\\n6204 DEPORTES SANTIAGO - PEÑALOLÉN`;
    let m;
    
    while ((m = regex.exec(str)) !== null) {
        // This is necessary to avoid infinite loops with zero-width matches
        if (m.index === regex.lastIndex) {
            regex.lastIndex++;
        }
        
        // The result can be accessed through the `m`-variable.
        m.forEach((match, groupIndex) => {
            console.log(`Found match, group ${groupIndex}: ${match}`);
        });
    }

    【讨论】:

    • 非常感谢您的回答,但在全文中有更多的数字,它不知道我需要它。这就是我将它与 _ 匹配的原因,因为它只出现在代码中。请如果您知道如何将整个代码匹配 _ 这将是惊人的。
    • 感谢您的帮助,我希望这对其他人有所帮助。我自己解决;当它带给我:“15317029-0_20190102_29_1_20190515\r”时,我只是:strCodigoPdf = strCodigoPdf.Substring(0,strCodigoPdf.Length()-0).Trim
    【解决方案2】:

    您也可以使用 split 来提取“10-K_20190304_29_1_20190515”部分。

    text.Split({“\r\n”},StringSplitOptions.None)(2)
    

    【讨论】:

      猜你喜欢
      • 2019-10-08
      • 1970-01-01
      • 2020-07-02
      • 2019-10-15
      • 1970-01-01
      • 2023-01-17
      • 2021-11-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多