Apex Method of the Day – String myString.split(String regExp)


We can split a String into parts using a token, which in this case is a space:

However, the following example, using “.” as a token will fail:

System.AssertException: Assertion Failed: Expected: 3, Actual:…

This is because the token is actually a regular expression, and some characters, like “.” have a special meaning within a regular expression. These special characters will need to be escaped with a backslash if they are to be treated literally – as is our intention.

However, by adding a backslash the following will actually fail to compile:

Invalid string literal ‘\.’. Illegal character sequence ‘\.’ in string literal

Backslash itself is a special character in Apex String literals, and so it needs to be further escaped with an additional backslash. Finally, the following gives the desired result:

You have to think of this as a two stage process. In the first stage Apex interprets the…

View original post 75 more words