Using string.split() with a decimal - not working

I'm trying to split a line of text into multiple parts. Each element of the text is separated by a period. I'm using string.split("."); to split the text into an array of Strings, but not getting anywhere.

Here is a sample of the code:

String fileName = "";

String[] fileNameSplit = fileName.split(".");


The funny thing is, when I try ":" instead of ".", it works? How can I get it to work for a period?


String.split() accepts a regular expression (regex for short) and dot is a special char in regexes. It means "match all chars except newlines". So you must escape it with a leading backslash. But the leading backslash is a special character in java string literals. It denotes an escape sequence. So it must be escaped too, with another leading backslash. Like this:


Try this one: fileName.split("\\.");


should be


. is special character and split() accepts regex. So, you need to escape the special characters.

A character preceded by a backslash (\) is an escape sequence and has special meaning to the compiler. Please read this documentation.

It's because the argument to split is a regular expression, and . means basically any character. Use "\\." instead of "." and it should work fine.

The regular expression for a literal period (as opposed to the any-character .) is \. (using the \ escape character forces the literal interpretation).

And, because it's within a string where \ already has special meaning, you need to escape that as well.

You need to escape the "." character because split accept regular expressions and the . means any character, so for saying to the split method to split by point you must escape it like this:

String[] array = string.split('\\.');

The split() takes in param a regex


String[] fileNameSplit = fileName.split("\\.");

Need Your Help

Automatically Add a Prefix to Column Names for @Embeddable Classes

java hibernate orm

I am developing a project in which I am persisting some POJOs by adding Hibernate annotations. One problem I am running into is that code like this fails, as Hibernate tries to map the sub-fields w...