我正在尝试从具有以下形式的字符串中捕获键值对:
a0=d235 a1=2314 com1="abcd" com2="a b c d"
使用来自的帮助这个帖子 https://stackoverflow.com/questions/168171/regular-expression-for-parsing-name-value-pairs,我能够编写以下正则表达式来捕获键值对:
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
EDIT:
可以通过根据是否有引号来捕获不同组中的值来实现上述目的。我正在为解析器编写这段代码,因此出于性能原因,我试图提出一个可以返回同一组编号中的值的正则表达式。
这个怎么样?这个想法是将最后一组分成两组。
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();
}
Update
这是针对更新后的问题的新解决方案。该正则表达式应用积极的前瞻和后瞻来确保存在引用而无需实际解析它。这样,上面的组 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);
}
Output
a0=d235
a1=2314
com1=abcd
com2=a b c d
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)