Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to split a string by using regex in java

Tags:

java

regex

I have a string like this

length 10 cm width 2 cm depth 0.5 cm / length 10 cm width 2 depth 0.5 cm

I want to get output like

length 10 cm
width 2 cm / width 2
depth 0.5 cm   

I tried this

public static void main(String []args) {
    String s = "length 10 cm width 2 cm depth 0.5 cm";
    String[] tok = s.split("(?<=\\d)\\s");
    for(int i=0; i< tok.length; i++) {
        System.out.println(tok[i]);
    }
}

It returns:

length 10
cm width 2
cm depth 0.5
cm
like image 548
srkprasad Avatar asked Sep 08 '26 14:09

srkprasad


1 Answers

Try the following match pattern.

(?: (?<![/*+-] )(?=length|width|depth))

Output

length 10 cm
width 2 cm
depth 0.5 cm / length 10 cm
width 2
depth 0.5 cm
like image 182
Reilas Avatar answered Sep 11 '26 03:09

Reilas