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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With