Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I use "." as a delimiter in split() function? [duplicate]

I have to take an input file, and append a number at the end to its name to use as output file. To achieve this, I use the following code:

String delimiter = ".";
String[] splitInput = inputLocation.split(delimiter);
String outputLocation = splitInput[0];

and I get the following exception:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0

I added the following statement to check the length of the splitInput array, and I get 0 as output.

System.out.println(splitInput.length);

Later, I used ".x" as delimiter (my file being .xls). I can use ".x" and achieve my purpose but I'm curious why won't "." work?

like image 697
DT7 Avatar asked Sep 06 '13 17:09

DT7


2 Answers

The split function uses regular expressions, you have to escape your "." with a "\"

When using regular expressions a "." means any character. Try this

String delimiter = "\\.x";

It should also be mentioned that \ in java is also a special character used to create other special characters. Therefore you have to escape your \ with another \ hence the "\\.x"


Theres some great documentation in the Java docs about all the special characters and what they do:

Java 8 Docs
Java 7 Docs
Java 6 Docs

like image 172
ug_ Avatar answered Oct 05 '22 12:10

ug_


The . has a special meaning: Any character (may or may not match line terminators). You can escape it prepending \ or use:

[.]x

e.g.:

String delimiter = "[.]x";

See more in http://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html

like image 45
Paul Vargas Avatar answered Oct 05 '22 12:10

Paul Vargas