34

I can hardly believe it but split() doesn't work on the . character:

String createDate = '01.2.2013';
String[] cd = createDate.split('.');
System.assertEquals(3, cd.size());   // Boom!

Tried with '\.' but it also doesn't work.

1 Answer 1

58

The separator string used in the split method is a regular expression and "." is a special character in regular expressions.

The regular expression for a literal "." is "\."

However "\" is also used to escape characters when expressing Strings in Apex, and so this character too needs escaping:

String[] cd = createDate.split('\\.');

The documentation provides an interesting example, if you need to use "\" as the separator:

List<String> parts = filename.split('\\\\');
3
  • 1
    Well that's logical...for a given value of "logical". Ta!
    – Marc
    Mar 1, 2013 at 3:47
  • 1
    This answer now blogged: wp.me/p2XgT8-4U Aug 30, 2013 at 9:16
  • Is there any method like c# Getfilename() in apex?
    – user22442
    Jul 26, 2015 at 12:52

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .