使用Java String split()作为简单"解析器"

时间:2016-05-03 03:37:16

标签: java string parsing

[{Action = GoTo,Title = 0001000a,Page = 1 XYZ 7 797 null},{Action = GoTo,Title = 0001000b,Page = 3 XYZ 7 797 null},{Action = GoTo,Title = 0001000c,Page = 5 XYZ 7 797 null},{Action = GoTo,Title = 0001000d,Page = 7 XYZ 7 797 null}]

我试图找到解析上述字符串的最简单方法,我只需要&#34;标题&#34;和&#34; Page&#34;。所以我想要一个简单的String [] = {&#34; 0001000a&#34;,&#34; 1&#34;,&#34; 0001000b&#34;,&#34; 3&#34; ...} < / p>

str.split("(\\[|, )\\{Action=GoTo, Title=|, Page=| XYZ \\d+ \\d+ null\\}");

我已经在一些在线js regexp测试器中测试了regexp,看起来很好,但是得到的String [] = {&#34; 0001000a&#34;,&#34; 1&#34;,&#34; &#34;,&#34; 0001000b&#34;,&#34; 3&#34;,&#34;&#34; ...},每个页面值后面一个额外的空字符串。

str.split("\\[|\\{Action=GoTo, Title=|, Page=| XYZ \\d+ \\d+ null\\}(, |\\])");

这个产生String [] = {&#34;&#34;,&#34; 0001000a&#34;,&#34; 1&#34;,&#34;&#34;,&#34 ; 0001000b&#34;,&#34; 3&#34; ...},每个标题值前面的空字符串。

似乎java并不喜欢&#34;,&#34;作为regexp,或者它可能是Java String.split()的工作方式!?

1 个答案:

答案 0 :(得分:1)

使用普通的Regexp而不是split()

可以轻松实现
String line = "[{Action=GoTo, Title=0001000a, Page=1 XYZ 7 797 null}, {Action=GoTo, Title=0001000b, Page=3 XYZ 7 797 null}, {Action=GoTo, Title=0001000c, Page=5 XYZ 7 797 null}, {Action=GoTo, Title=0001000d, Page=7 XYZ 7 797 null}]";
ArrayList<String> list = new ArrayList<>();
Pattern pattern = Pattern.compile("Title=([^,]+), Page=([^}]+)}");
Matcher matcher = pattern.matcher(line);
while (matcher.find()) {
    list.add(matcher.group(1));
    list.add(matcher.group(2));
}
String[] foo = list.toArray(new String[list.size()]);
相关问题