Here’s the code I’m using :
public class splitText {
public static void main(String[] args) {
String x = "I lost my Phone. I shouldn't drive home alone";
String[] result = x.split(".");
for (String i : result) {
System.out.println(i);
}
}
}
Compiles perfectly, but nothing happens at runtime. What am I doing wrong?
String.split(String regex)takes a regular-expression pattern. It just so happens that.in regex is a metacharacter that matches (almost) any character, hence whysplit(".")doesn’t work the way you expected.You can escape the
.by preceding it with a backslash. As a Java string literal, this is"\\.". The\is doubled because\itself is a Java escape character."\\."is aStringof length 2, containing a backslash and a period.If you’re given an arbitrary
Stringthat is to be matched literally (or if you just don’t care to escape them yourself), you can usePattern.quote. It’ll make a pattern to literally match a givenString.See also
This is provided for educational purposes only:
This prints:
References
Related questions
(?<=#)[^#]+(?=#)work?