How to Split the special characters using apex class

Its possible to split the string using the characters/letters using the SPLIT method using apex class.
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:
Splitting a string using ‘.’
String[] d = createDate.split(‘\\.’);
system.debug(d[0]);
system.debug(d[1]);

Same way we can split the other special characters like @,&,$,!,etc

Splitting a string using ‘|’
| ====> ‘|’
String[] d = createDate.split(‘\\|’);
system.debug(d[0]);
system.debug(d[1]);

Splitting a string using ‘\’

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

List<String> parts = filename.split('\\\\');

Written by 

2x Salesforce MVP | Platform Champion | 18x Salesforce Certified | MuleSoft Certified | 8x Trailhead Ranger | TechForce Services | Sydney | Australia

Leave a Reply

Your email address will not be published. Required fields are marked *

*