March 30, 2010

String Splitting

Another quick Apex heads up, if you have a string which contains pipe delimited values (e.g. 'hello|world') then if you want to grab the parts using the .split() string method you need to doubly escape the pipe as it's a special character (OR) for regex:

string strHello = 'hello|world'; 
list<string> liParts = strHello.split('\\|');

If you just use '|' you'll find split() returns a list of every character, not very useful in this situation! The reason you need to doubly escape it is because it needs to be escaped for the regex, i.e. '\|' but the backslash itself needs to be escaped, so '\\|' results in '\|' being used as the regex for the operation.