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

25 comments:

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

code:
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="hjx@umich.edu".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?

Anonymous said...

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

Unknown said...

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

Anonymous said...

Thx

Sureszzzz said...

thanks

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

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

what is the use of [0]?

thanks!

Anonymous said...

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

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.

Unknown said...

Thankyou for you information.
Thankyou verymuch

Anonymous said...

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

best dissertation services

David Machado Santos Filho 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:

a.split("\\\\.")

:-)

Anonymous said...

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

Shivam Kumar said...

Nice Article... visit more java examples

Unknown said...

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

Java Training in Chennai