Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Having trouble with Splitting text

Tags:

java

split

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?

like image 833
DM_Morpheus Avatar asked Jul 16 '10 13:07

DM_Morpheus


2 Answers

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 why split(".") 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 a String of length 2, containing a backslash and a period.

If you're given an arbitrary String that is to be matched literally (or if you just don't care to escape them yourself), you can use Pattern.quote. It'll make a pattern to literally match a given String.

See also

  • regular-expressions.info/The Dot Matches (Almost) Any Character

This is provided for educational purposes only:

    String text =
        "Wait a minute... what?!? Oh yeah! This is awesome!!";

    for (String part : text.split("(?<=[.?!]) ")) {
        System.out.println(part);
    }

This prints:

Wait a minute...
what?!?
Oh yeah!
This is awesome!!

References

  • regular-expressions.info/Character Class

Related questions

  • How does the regular expression (?<=#)[^#]+(?=#) work?
like image 124
polygenelubricants Avatar answered Sep 24 '22 13:09

polygenelubricants


String.split uses a regex, so dot (.) means "anything". You need to escape the dot

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.trim());
    }
}

gives :

I lost my Phone
I shouldn't drive home alone
like image 26
Jean-Philippe Caruana Avatar answered Sep 22 '22 13:09

Jean-Philippe Caruana