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