0

[{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}]

I'm trying to find the simplest way to parse the above String, all I need are "Title" and "Page". So I want a simple String[] = {"0001000a","1","0001000b","3"...}

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

I have tested the regexp in a few online js regexp tester, it seems fine, but the resulting String[] = {"0001000a","1","","0001000b","3",""...}, an extra empty string after each page value.

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

This one produces String[] = {"","0001000a","1","","0001000b","3"...}, an empty string in front of every title value.

It seems like java doesn't like ", " as regexp, or it could be the way that Java String.split() works!?

2
  • Why are you using split(), when this is obviously not a simple case. Regexp would be far better suited Commented May 3, 2016 at 3:41
  • hi Tibrogargan, I thought it's simple enough to use split(). Anyway, I'm open to other ideas. Commented May 3, 2016 at 3:49

1 Answer 1

1

This is easily implemented using plain Regexp instead of 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()]);
Sign up to request clarification or add additional context in comments.

1 Comment

Thx Tibrogargan, I'm so green in regexp, thanks for the example.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.