Question

My String is ,

   String myString = "Hello   Boom,  Ho3w are || You ? Are  ^  you ," fr45ee   now ?";

I tried the below to split the string as ,

"Hello,Boom,Ho3w,are,You,Are,you,fr45ee,now" - where comma indicates the separation of String to String array. My code is

  String[] temp = data.split("\\s+\\^,?\"'\\|+");

But it is no working . Hope You people helps.Thanks.

Was it helpful?

Solution

Your example won't compile as you have an unescaped double quote in your myString variable.

However, assuming it is escaped...

//                                                               | escaped " here
String myString = "Hello   Boom,  Ho3w are || You ? Are  ^  you ,\" fr45ee   now ?";
//                 | printing array
//                 |               | splitting "myString"...
//                 |               |               | on 1 or more non-word 
//                 |               |               | characters
System.out.println(Arrays.toString(myString.split("\\W+")));

Output

[Hello, Boom, Ho3w, are, You, Are, you, fr45ee, now]

OTHER TIPS

I believe this should work:

String myString = "Hello   Boom,  Ho3w are || You ? Are  ^  you ,\" fr45ee   now ?";
String[] arr = myString.split("\\W+");
//=> [Hello, Boom, Ho3w, are, You, Are, you, fr45ee, now]

If you literally only trying to split on the characters in your original regex, you should factor out the + and put everything into a character class.

public class Split {
    public static void main(String[] args) {
        String myString = "Hello   Boom,  Ho3w are || You ? Are  ^  you ,\" fr45ee   now ?";
        String[] temp = myString.split("[\\s\\^,?\"'\\|]+");
        for (int i = 0; i < temp.length; i++)
            System.out.println(temp[i]); 
    }
}

Output:

Hello
Boom
Ho3w
are
You
Are
you
fr45ee
now
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top