-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?

QuantumMechanic
  • 13,795
  • 4
  • 45
  • 66
Terry Li
  • 16,870
  • 30
  • 89
  • 134
  • 4
    Please don't post screenshots of text. Post text instead. – Oliver Charlesworth May 20 '12 at 23:32
  • You could use a StringTokenizer instead. – OmniOwl May 20 '12 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? – user unknown May 20 '12 at 23:33
  • @Vipar StringTokenizer has actually be deprecated in favour of split. – dann.dev May 20 '12 at 23:37
  • Really? Interesting. I didn't know this. – OmniOwl May 20 '12 at 23:38
  • 1
    Possible dup of http://stackoverflow.com/a/7904762/1330481 – UNECS May 20 '12 at 23:40
  • @dann.dev are you sure? The docs have no mention of it even for Java7 http://docs.oracle.com/javase/7/docs/api/java/util/StringTokenizer.html – Chip May 20 '12 at 23:49
  • @Chip interesting, it seems it 'was' deprecated, see this question. http://stackoverflow.com/questions/6983856/why-is-stringtokenizer-deprecated – dann.dev May 20 '12 at 23:59
  • @Vipar see the above link, seems I'm wrong and it's not deprecated anymore – dann.dev May 20 '12 at 23:59
  • @dann.dev You are **NOT** wrong :) Looking at the javadoc again, the part about the **legacy code** is buried deep inside it. It's strange that they did not mark it as deprecated like they normally do. Sorry for the confusion, I did not know that line was there. So final word - it is not formally deprecated, but the use is **discouraged**. – Chip May 21 '12 at 00:04
  • @Chip if memory serves me (and sometimes it doesn't) i have a feeling when it first became legacy, eclipse would suggest that is was deprecated, which may be where the confusion arose. – dann.dev May 21 '12 at 00:06

1 Answers1

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 : \

Chip
  • 3,226
  • 23
  • 31