Splitting a string in Java into ";" but not into "\\;"

In Java, I am trying to use a method String.split()to divide a string into ";", but not into "\\\\;". (2 backslashes followed by a semicolon)

Ex: "aa;bb;cc\\;dd;ee\\;;ff"should be divided into:

aa

bb

cc\\;dd

ee\\;

ff

How to do this using regex?

Marcus

+3
source share
3 answers

Using

"aa;bb;cc\\;dd;ee\\;;ff".split("(?<!\\\\);");

(? <!...) " lookbehind". ; NOT, , . - . , , :

(?<!\\);
+10

lookbehind, (?<!a)b. b, a. - :

(?<!\\\\);
+5

Here is sample code from. as a separator:

String p = "hello.regex\\.brain\\.twister";
System.out.println( p );
for (String s : p.split( "(?<!\\\\)\\.", -1 )) {
  System.out.println( "-> "+ s );
}

Will Ouptut:

hello.regex\.brain\.twister
-> hello
-> regex\.brain.\twister
0
source

Source: https://habr.com/ru/post/1785231/


All Articles