+ Start a Discussion
jhartfieldjhartfield 

Bug? 'Split' function does not work for '*' or '+'

I randomly was trying a split today on a '*' field and got the following error:

 

System.StringException: Invalid regex: Dangling meta character '*' near index 0 * ^

 

Out of curiosity, I tried to split on '+' and got the same error.  

 

This is easily reproducible for me by running the following code in the execute anonymous window - can anyone else  confirm?

string sString = 'someStuff'; string[] splitted = sString.split('*');

 

 

Best Answer chosen by Admin (Salesforce Developers) 
bob_buzzardbob_buzzard

The following allows the text to be split on the '*' character:

 

string sString = 'some*Stuff'; string[] splitted = sString.split('\\*'); system.debug('Splitted = ' + splitted);

 


All Answers

bob_buzzardbob_buzzard

This is because the split method takes a regular expression, not a vanilla string. 

 

The '*' character means match the previous character zero or more times, thus it is not valid to specify it on its own.

 

The '+' character means match the previous character one or more times, again not valid without a preceding character.

 

Full details on the regexp can be found at:  http://java.sun.com/j2se/1.5.0/docs/api/java/util/regex/Pattern.html

bob_buzzardbob_buzzard

The following allows the text to be split on the '*' character:

 

string sString = 'some*Stuff'; string[] splitted = sString.split('\\*'); system.debug('Splitted = ' + splitted);

 


This was selected as the best answer
jhartfieldjhartfield

Thanks Bob, I had not realized that the split method used a regular expression!

 

I do see that it is documented here, for anyone stumbling on this in the future:

http://www.salesforce.com/us/developer/docs/apexcode/Content/apex_methods_system_string.htm