[{Action = GoTo,Title = 0001000a,Page = 1 XYZ 7797 null},{Action = GoTo,Title = 0001000b,Page = 3 XYZ 7797 null},{Action = GoTo,Title = 0001000c,Page = 5 XYZ 7 797 null},{Action = GoTo,Title = 0001000d,Page = 7 XYZ 7797 null}]
我试图找到最简单的方法来解析上述字符串,我需要的只是“标题”和“页面”。所以我想要一个简单的String [] = {“ 0001000a”,“ 1”,“ 0001000b”,“ 3” ...}
str.split("(\\[|, )\\{Action=GoTo, Title=|, Page=| XYZ \\d+ \\d+ null\\}");
我已经在一些在线js regexp测试器中测试了regexp,看起来不错,但是生成的String [] = {“ 0001000a”,“ 1”,“”,“ 0001000b”,“ 3”,“” ...} ,每个页面值后面的一个额外的空字符串。
str.split("\\[|\\{Action=GoTo, Title=|, Page=| XYZ \\d+ \\d+ null\\}(, |\\])");
这会产生String [] = {“”,“ 0001000a”,“ 1”,“”,“ 0001000b”,“ 3” ...},这是每个标题值前面的空字符串。
看来Java不喜欢regexp作为“,”,或者它可能是Java String.split()起作用的方式!
使用纯正则表达式而不是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()]);
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句