Reputation: 141
I am having an issue with lookbehind in java. The following method
public static void main (String[] args) throws java.lang.Exception
{
String num = "1E-12x10";
String[] numArr = num.split("(?<!E)\\-");
System.out.println(numArr[0]);
}
produces the output 1E-12x10 as expected - it does not split on the '-'.
The following method
public static void main (String[] args) throws java.lang.Exception
{
String num = "1E-12x10";
String[] numArr = num.split("[x\\-]");
System.out.println(numArr[0] + " " + numArr[1] + " " + numArr[2]);
}
also produces the expected output 1E 12 10, splitting on both 'x' and '-'.
But when I try the following method
public static void main (String[] args) throws java.lang.Exception
{
String num = "1E-12x10";
String[] numArr = num.split("[x(?<!E)\\-]");
System.out.println(numArr[0] + " " + numArr[1] + " " + numArr[2]);
}
I expect the string to split on 'x' but not on '-'. However, what happens is that it splits on 'x', 'E' and '-'. I am not quite sure what's going on here.
Upvotes: 2
Views: 59
Reputation: 148990
You can't place lookbehinds inside a character class. You need to use an alternation, like this:
String[] numArr = num.split("x|(?<!E)-");
This will split the string on any x
character, or any -
not preceded by an E
character. Also note that in this case the \\
is not necessary before the -
.
Upvotes: 3