Reputation: 55
Im trying to use the Split Function in Java. The character i'm trying to split at is ;
.
So my code is like this:
string.split(";");
However, inside the string I have many escaped \;
. I wanted to a regex which would not split at \;
but only split at where the ;
is on its own.
Example of String:
sometexthere\;shhshshshhs;shhshshshshs\;dddddd;
Expected Result:
[0] sometexthere\;shhshshshhs;
[1] shhshshshshs\;dddddd;
Any Help would be appreciated. Thanks!
Upvotes: 2
Views: 137
Reputation: 195049
try this:
str.split("(?<!\\\\);");
EDIT
if you do want to have the spliter (the ;
) in result array:
str.split("(?<=[^\\\\];)");
Note that single look-behind is sufficient for this problem.
and this time, I did a test:
final String str = "sometexthere\\;shhshshshhs;shhshshshshs\\;dddddd;";
System.out.println(Arrays.toString(str.split("(?<=[^\\\\];)")));
it outputs:
[sometexthere\;shhshshshhs;, shhshshshshs\;dddddd;]
Upvotes: 5
Reputation: 124225
Try with split("(?<=(?<!\\\\);)")
if you don't want to remove ;
but just split after it. We are using here double look-behind mechanisms:
(?<=...)
(?<!...)
(?<=;)
will find places that has ;
before it, but we also have to make sure that ;
doesn't have \
before, so we can write it as (?<=(?<!\\\\);)
.
Upvotes: 2