0

I wanna split the content of a string variable, but I wanna use the point as a delimiting regular expression, my code doesn't work.

public class Test {

    public static void main(String [] a){
        String ch = "r.a.c.h.i.d";
        String[] tab;
        tab=ch.split(".");
        System.out.println(tab.length);
        for(String e : tab)System.out.println(e);
    }
}
Pang
  • 9,564
  • 146
  • 81
  • 122
SegTree
  • 57
  • 1
  • 2
  • 10

3 Answers3

1

Change tab=ch.split("."); to tab=ch.split("\\.");. You need to escape the dot because otherwise it's treated as a special character in the regex passed to split.

Mateusz Dymczyk
  • 14,969
  • 10
  • 59
  • 94
1
tab = ch.split("\\.");

One slash is the escape character for the regex. But in Java you need to have a second slash because you have to escape the first slash.

Jose Martinez
  • 11,452
  • 7
  • 53
  • 68
0

Yes, it's possible. In a regular expression, . means any character.

Predefined character classes

.       Any character (may or may not match line terminators)

So you must escape it to provide the literal . meaning. Escape it with a backslash character, providing two backslashes, because Java needs the backslash character itself escaped.

Use the regular expression "\\.".

In general, to get the literal characters out of an expression that may contain special-meaning characters, you can use the Pattern.quote method.

This method produces a String that can be used to create a Pattern that would match the string s as if it were a literal pattern.

split(Pattern.quote("."))
Community
  • 1
  • 1
rgettman
  • 176,041
  • 30
  • 275
  • 357