正则表达式用于匹配特定单词并忽略换行

时间:2019-05-08 05:47:55

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

全文=

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

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

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

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

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

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

3 个答案:

答案 0 :(得分:3)

This expression可能会这样做,并且我们当然可以根据需要添加更多边界:

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

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

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

enter image description here

编辑:

然后,this expression可以通过创建3个捕获组来帮助我们做到这一点:

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

enter image description here

测试RegEx 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}`);
    });
}

测试RegEx 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}`);
    });
}

答案 1 :(得分:2)

另一种选择是使用捕获组,而不是使用正向查找:

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

Regex demo

答案 2 :(得分:1)

这种模式如何:

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

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

Demo

相关问题