I was wondering what the following line would do:
String parts = inputLine.split("\\s+");
Would this simply split the string at any spaces in the line? I think this a regex, but I've never seen them before.
Yes, as documentation states split
takes regex as argument.
In regex \\s
represents character class of containing whitespace characters like:
\\t
," "
,\\n
\\r
+
is quantifier which can be read as " once or more " which makes \\s+
representing text build from one or more whitespaces.
We need to write this regex as "\\\\s+
(with two backslashes) because in String \\
is considered special character which needs escaping (with another backslash) to produce \\
literal.
So split("\\\\s+")
will produce array of tokens separated by one or more whitespaces. BTW trailing empty elements are removed so "abc ".split("\\\\s+")
will return array ["a", "b", "c"]
not ["a", "b", "c", ""]
.
Yes, though actually any number of space meta-characters (including tabs, newlines etc). See the Java documentation on Patterns .
It will split the string on one (or more) consecutive white space characters. The Pattern
Javadoc describes the Predefined character classes (of which \\s
is one) as,
Predefined character classes
. Any character (may or may not match line terminators) \\d A digit: [0-9] \\DA non-digit: [^0-9] \\s A whitespace character: [ \\t\\n\\x0B\\f\\r] \\SA non-whitespace character: [^\\s] \\w A word character: [a-zA-Z_0-9] \\WA non-word character: [^\\w]
Note that the \\\\
is to escape the back-slash as required to embed it in a String
.
Yes, and it splits both tab and space:
String t = "test your function aaa";
for(String s : t.split("\\s+"))
System.out.println(s);
Output:
test your function aaa
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.