4

我正在尝试从具有以下形式的字符串中捕获键值对:

a0=d235 a1=2314 com1="abcd" com2="a b c d"

使用这篇文章的帮助,我能够编写以下捕获键值对的正则表达式:

Pattern.compile("(\\w*)=(\"[^\"]*\"|[^\\s]*)");

问题是该模式中的第二组也捕获了引号,如下所示:

a0=d235
a1=2314
com1="abcd"
com2="a b c d"

如何排除引号?我想要这样的东西:

a0=d235
a1=2314
com1=abcd
com2=a b c d

编辑:

根据是否有引号,可以通过捕获不同组中的值来实现上述目的。我正在为解析器编写此代码,因此出于性能原因,我试图提出一个可以返回同一组号中的值的正则表达式。

4

2 回答 2

10

这个怎么样?这个想法是将最后一组分成两组。

Pattern p = Pattern.compile("(\\w+)=\"([^\"]+)\"|([^\\s]+)");

String test = "a0=d235 a1=2314 com1=\"abcd\" com2=\"a b c d\"";
Matcher m = p.matcher(test);

while(m.find()){
    System.out.print(m.group(1));
    System.out.print("=");
    System.out.print(m.group(2) == null ? m.group(3):m.group(2));
    System.out.println();
}

更新

这是针对更新问题的新解决方案。这个正则表达式应用了积极的前瞻和后瞻来确保有一个引用而不实际解析它。这样,上面的第 2 组和第 3 组可以放在同一个组中(下面的第 2 组)。返回组 0 时无法排除引号。

Pattern p = Pattern.compile("(\\w+)=\"*((?<=\")[^\"]+(?=\")|([^\\s]+))\"*");

String test = "a0=d235 a1=2314 com1=\"abcd\" com2=\"a b c d\"";
Matcher m = p.matcher(test);

while(m.find()){
    print m.group(1);
    print "="
    println m.group(2);
}

输出

a0=d235
a1=2314
com1=abcd
com2=a b c d
于 2012-07-13T21:34:27.427 回答
0

使用此正则表达式(\w+)=(("(.+?)")|(.+?)(?=\s|$))键和值包含在正则表达式组中

于 2012-07-13T21:28:20.080 回答