【问题标题】:RegEx for matching specific words and ignoring new lines用于匹配特定单词并忽略新行的正则表达式
【发布时间】:2019-09-25 19:21:01
【问题描述】:

全文 =

"
......
A= 
B= 12345 
....."

我想在 A= 和换行符之间得到空字“”。 并希望在 B= 和换行符之间获得“12345”。

如何使用正则表达式获取单词?

(?<=A=)\s*(\S*)\s* 

(?<=B=)\s*(\S*)\s* 

但是,它也带来了下一行内容。

【问题讨论】:

    标签: regex powershell regex-lookarounds regex-group regex-greedy


    【解决方案1】:

    This expression 可能会这样做,如果需要,我们当然可以添加更多边界:

    ^([A-B=]+\s)([0-9]+|)
    

    我们有两个捕获组,我们可以使用 $1$2 简单地调用它们。

    图表

    此图显示了表达式的工作原理,我们可以在 link 中可视化其他表达式:

    编辑:

    那么,this expression 可能会通过创建 3 个捕获组来帮助我们做到这一点:

    ^([A-Z]+)([=\s]+)([A-z0-9-]+)
    

    正则表达式 1 测试

    const regex = /^([A-B=]+\s)([0-9]+|)/gm;
    const str = `"
    ......
    A= 
    B= 12345 
    ....."`;
    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}`);
        });
    }

    正则表达式 2 测试

    const regex = /^([A-Z]+)([=\s]+)([A-z0-9-]+)/gm;
    const str = `ADFJE = 12313-asrn[5493]h`;
    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}`);
        });
    }

    【讨论】:

    • 其实我想得到 "123d-a5srn[5493]h" 全文 = " ADF3JE = 123d-a5srn[5493]h RFD2AE = 133sdn[1-3-93]h "跨度>
    • 您的视觉解释实际上与您答案中的真实内容相去甚远,恕我直言。我建议删除它们(您可以假设读者至少具有正则表达式的基本工作知识)。
    【解决方案2】:

    另一个替代使用正向回溯的选项是使用捕获组:

    ^[A-Z]+[ ]*=[ ]*(\S*)
    
    • ^ 字符串开始
    • [A-Z]+ 匹配 1+ 次 A-Z
    • [ ]*= 匹配 0+ 次空格后跟 =
    • [ ]*= 匹配 0+ 次空格
    • (\S) 在匹配 0+ 次非空白字符的组中捕获(这将包含您的值)

    Regex demo

    【讨论】:

    • (\S*)\s* 可能仍然存在使用 Powershell 换行到下一行的问题。
    • @TimBiegeleisen 你是对的,因为\s,谢谢你指出这一点!。我已经更新了。
    【解决方案3】:

    这个模式怎么样:

    (?<=[A-Z]=)[ ]*(\S*)
    

    此模式通过首先只允许A=(或B= 等)之后的空格来避免换行到下一行的问题。这意味着对于A= 行,它后面只有一个换行符,[ ]* 将匹配零次。其次,对于内容它只使用(\S*),也不会消耗空格并换行到下一行。

    Demo

    【讨论】:

      猜你喜欢
      • 2018-01-02
      • 2017-10-29
      • 2013-06-10
      • 1970-01-01
      • 1970-01-01
      • 2019-09-29
      • 1970-01-01
      • 2013-02-08
      • 2019-09-25
      相关资源
      最近更新 更多