-2
import java.util.regex.*;

public class Splitter {
    public static void main(String[] args) throws Exception {
        Pattern p = Pattern.compile("[,\\s]+");
        String[] results = p.split("one,two, three   four ,  five");
        for (String result : results) {
            System.out.println(result);
        }
    }
}

The splitter is either a comma or a whitespace or a combination of any number of them. I thought the regular expression for it should be [,\s]+. Why was there an extra backslash in the example?

11
  • 4
    Please don't post screenshots of text. Post text instead. Commented May 20, 2012 at 23:32
  • You could use a StringTokenizer instead. Commented May 20, 2012 at 23:33
  • 1
    What kind of asking a question is that? Do you want to prevent possible helpers to cut and paste your code to test/improve it? Commented May 20, 2012 at 23:33
  • @Vipar StringTokenizer has actually be deprecated in favour of split. Commented May 20, 2012 at 23:37
  • 1
    Possible dup of stackoverflow.com/a/7904762/1330481 Commented May 20, 2012 at 23:40

1 Answer 1

5

The extra \ is to escape the next backslash. In any Java string "\\" means "\".

This is because the '\' is a special character. You must have seen "\n" used to mean newline right? So to put a literal \ in a string you use "\\".

For example try System.out.println("Here\'s a backslash : \\").

This will print : Here's a backslash : \

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

2 Comments

Why is the first backslash gone in the output?
@TerryLiYifeng \' means the character '. The character ' is not required to be escaped in a string but \' means '. Try it out.

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.