4

I am trying to read a text file, split the contents as explained below, and append the split comments in to a Java List.

The error is in the splitting part.

Existing String:

a1(X1, UniqueVar1), a2(X2, UniqueVar1), a3(UniqueVar1, UniqueVar2)

Expected—to split them and append them to Java list:

a1(X1, UniqueVar1)
a2(X2, UniqueVar1)
a3(UniqueVar1, UniqueVar2)

Code:

subSplit = obj.split("\\), ");
for (String subObj: subSplit)
{
    System.out.println(subObj.trim());
}

Result:

a1(X1, UniqueVar1
a2(X2, UniqueVar1
...

Please suggest how to correct this.

4
  • 1
    Dude, use: str.split(", "); Commented Apr 3, 2017 at 6:40
  • 3
    The token around which is split won't get included in the result again. Solution would be to just reappend the token. Commented Apr 3, 2017 at 6:40
  • 4
    you are removing the ")," when you split/trim. Easiest way would be to append a closing bracket. Commented Apr 3, 2017 at 6:41
  • 1
    @user218046 that won't help. Consider "a1(X1, UniqueVar1), a2(X2, UniqueVar1)," this string would be split into "a1(X1", "UniqueVar1)", "a2(X2", "UniqueVar1)". Commented Apr 3, 2017 at 6:42

1 Answer 1

9

Use a positive lookbehind in your regular expression:

String[] subSplit = obj.split("(?<=\\)), ");

This expression matches a , preceded by a ), but because the lookbehind part (?<=\\)) is non-capturing (zero-width), it doesn't get discarded as being part of the split separator.

More information about lookaround assertions and non-capturing groups can be found in the javadoc of the Pattern class.

Sign up to request clarification or add additional context in comments.

1 Comment

this is great. Could you please explain the split condition?

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.