Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split and replace Java string

Tags:

java

string

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.

like image 358
vikky 2405 Avatar asked Jan 04 '23 06:01

vikky 2405


1 Answers

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.

like image 114
Robby Cornelissen Avatar answered Jan 14 '23 06:01

Robby Cornelissen