1
votes

I have the following String:

"location-string:location-string:location-C?:\string"

which I would like to split into the following three Strings:

location-string location-string location-C?:\string

What should the regex expression be when using String.split(regex)?

Basically, I want to split on colon ':' characters except those that are preceded by a '?' character!

Thanks in advance, PM.

2

2 Answers

6
votes

You could use negative lookbehind. It matches the colon which was not preceeded by ?

(?<!\?):

Java regex would be,

"(?<!\\?):"

DEMO

0
votes

You could use a split() with limit.

public static void main(String[] args) {
    String s = "location-string:location-string:location-C?:\\string";
    System.out.println(Arrays.toString(s.split(":", 3))); 
}

O/P :

[location-string, location-string, location-C?:\string]