Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex based string split in Java

Tags:

java

regex

String delimiterRegexp = "(;|:|[^<]/)";
String value = "get/time/pick me <i>Jack</i>";
String[] splitedTexts = value.split(delimiterRegexp);
for (String text : splitedTexts) {
System.out.println(text);
}

Output:
ge
tim
pick me <i>Jack</i>

Expected Result: 
get
time
pick me <i>Jack</i>

A character is getting added as delimeter along with /. Could anyone help me out to write regex to split text based on delimeter"/" and it should ignore xml end tag"

like image 665
Vignesh Avatar asked Jun 03 '26 19:06

Vignesh


2 Answers

Your regex should be like this:

(;|:|(?<!<)/)

with a negative lookbehind, demo: https://regex101.com/r/2k1WI5/1/

Your current regex [^<]/ will match basically any character that is not < followed by / even \n, space, and Japanese characters.

That's why you are losing some letters as they are considered as part of the separator.

Following The fourth bird recommendation, you can even simplify the regex into: ([;:]|(?<!<)/)

like image 141
Allan Avatar answered Jun 06 '26 07:06

Allan


[^<]/ will match e/ and t/

use a lookbehind instead, it will have the wanted behaviour to only consider / as separator if it's not a closing tag

On regex101.com

(?<!<)/

The whole regex

(;|:|(?<!<)/)
like image 41
Yassin Hajaj Avatar answered Jun 06 '26 08:06

Yassin Hajaj