0

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.

1
  • 1
    myString is not the correct string. you need to escape the " character. Commented May 9, 2014 at 10:09

3 Answers 3

7

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]
Sign up to request clarification or add additional context in comments.

Comments

5

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]

Comments

2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.