Friday, January 30, 2009

Java tip: how to split a string with "." (a dot)

String a = "a.jpg";
String str = a.split(".")[0];
This will throw ArrayOutOfBoundException
Why is this?
This is because "." is a reserved character in regular expression, representing any character.
Instead, we should use the following statement:
String str = a.split("\\.")[0];
When the code is compiled, the regular expression is known as "\.", which is what we want it to be


Anonymous said...

hi i am splitting an email address
first i split at @
then the second part i split at "." to get domain but gives error

result = s[j].split("@");
uname[j] = result[0];
res = result[1].split("\\.");
domain[j] = res[res.length-1];

uname is stored properly
problem in third line
gives error 1 at cmd prompt

Junxian Huang said...

String[] result="".split("@");
String uname = result[0];
String[] res = result[1].split("\\.");
String domain = res[res.length-1];
System.out.println(uname + " " + domain);

I run it without any error on my PC using JDK 1.6.
Can you post your error messages here?

gokay aydin said...

thanks for the practical info. may the force with you!

misterdom said...

Thanks for that! The split(".") was driving me nuts ;-)

Anonymous said...


Sureszzzz said...


Anonymous said...

Thanks very help full

Anonymous said...

thank you veryyyyyyyyyyyyyy much!

OutOfMemoryError in Java said...

here is another good link on split String in Java which compares both split and StringTokenizer.

Anonymous said...

very nice!

Anonymous said...

Great, thanks a lot

z said...

Great help, Thanks :D

at_198x said...

Thanks. You're awesome. Important thing like this is not mentioned in Javadoc.

kj pogi said...

Hi, I have a follow up question

String str = a.split("\\.")[0];

what is the use of [0]?


Anonymous said...

even it comes late, there are two steps in one.
String[] aSplitted = a.split("\\.");

split returns an array, so you can handle it as an array.

Anonymous said...

Good to know!
Thanks for sharing

Anonymous said...

great! Saved a lot of my time.

Anonymous said...

thx bro

Anonymous said...

Oh yeah you saved me so much.

Irudaya Raj said...

Thankyou for you information.
Thankyou verymuch

Tutorsindia said...

Great article ..I need some more information about Java Swing..Can anyone help me out?

best dissertation services

David Machado said...

DOT is a reserved simbol on regular expressions. So, it must be escaped as "\."

BUT \ is ALSO a reserved simbol. Must be escaped too: "\\."

AT LAST, \ is a reserved simbol in java strings. The correct solution must be:



Anonymous said...

Thanks a lot. I spent many time to resolve it!

Java Proficiency said...

Nice Article... visit more java examples

venkat ramana said...

Great and Nice article... Thanks for sharing your information and Views..

Java Training in Chennai