Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

regex split based on exact character except when escaped with a backslash before it

Need to split a string using delimiter, but only if there is no backslash before the delimiter.

ex: if there is abc \:abc - do not split it as : has backslash before it.

if the string is abc : abc - need to split as abc, abc.

The delimiters can be :,|,& etc.

like image 704
Paulena Avatar asked Oct 15 '25 15:10

Paulena


1 Answers

Use a negative look-behind (?<!...). To match a literal backslash \, you have to escape twice. Once to escape because it's a string literal, and again because it's a regex escape character.

String[] parts = string.split("(?<!\\\\)[:,|&]");
like image 121
4castle Avatar answered Oct 17 '25 03:10

4castle