thieba
thieba

Reputation: 41

split string by multple white-space and characters

I have this string.

File Name : foto1.jpg

I want to put the elements in a string of 2 fields like {"File Name", "foto1.jpg"}. How can I do this in java?

I'm trying...

split("\\s{2,}:\\s") 

...but it doesn't work.

Upvotes: 4

Views: 114

Answers (2)

Raj K
Raj K

Reputation: 470

You can just spilt it based on regx as : in your case. Below is the example to get it.

public class StringSplit {
    public static void main(String[] args) {
        String a = "File Name : foto1.jpg";
        String[] values = a.split(":", 2);
        System.out.println(values[0].trim());
        System.out.println(values[1].trim());
    }
}

Upvotes: 1

TheLostMind
TheLostMind

Reputation: 36304

\\s+:\\s+ should work for you :

public static void main(String[] args) throws Exception {
    String s = "File Name : foto1.jpg";
    String[] arr = s.split("\\s+:\\s+"); // + means one or more
    System.out.println(Arrays.toString(arr));

}

O/P :

[File Name, foto1.jpg]

Upvotes: 1

Related Questions