-2

I want to split a string in java with white spaces. I know that the below line of code does it.

String s[] = str.split("\\\s+");

Here split function takes the regex by which the string must be split. So when I want to split string str through one or more spaces, I should pass \s+ as regex, then why is \\\s+ used?

2
  • 5
    Triple backslash doesn't compile in java. The proper regex is \\s+ in java, as 1 backslash is needed to escape the second Commented Jul 17, 2019 at 9:06
  • You need to use double backslash. Backslash is a special symbol in Java and you have to use escape character. For backslash escape character is double backslash Commented Jul 17, 2019 at 9:10

2 Answers 2

1

This will do the split

String s[] = n.split("\\s+");

You don't need a third slash'\' - you get Compile Error.
And first '\' is for escaping the second '\'. Used as an escape character for '\s'.

Sign up to request clarification or add additional context in comments.

Comments

1

Like Ismail said, you don't need the third backslash. In your regex you want to use \s so in Java you also need to escape your backslashes for your tags.

Solution:
Why does this Java regex cause "illegal escape character" errors?

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.