Is there an easy and elegant way to add characters in a String at specified places around found characters?

The way I started thinking was like this:

String regExp = '[\\d]';
String toFormat = '1 and 2';
String formatted = toFormat.replaceAll(regExp, '[ ]');

Now what happens, is that every numerical character is replaced by '[ ]'. My goal is not to have those characters replaced, but embraced by the bracets:

[1] and [2]

Maybe I am not thinking in the right direction at all, does Salesforce offer specific solutions to this?


Use grouping to grab the value that was found, then use it in the replacement by re-calling it with the $1.


// note the parentheses for grouping in the pattern
String regExp = '([\\d])';
String toFormat = '1 and 2';
// replace string uses $1 to recall the first group in the pattern
String formatted = toFormat.replaceAll(regExp, '[$1]');


06:22:20.021 (21168207)|USER_DEBUG|[4]|DEBUG|[1] and [2]
|improve this answer|||||

I'm doing like this :

String source = '1 and 2';
String[] chars = source.split('');
// The 1st element in an Apex '' split is garbage; remove it
String result ='';

for(String s : chars) {
    if(s.isNumeric()) {
        result += '[' + s + ']';
    } else {
        result += s;
system.debug(result); // Display [1] and [2]
|improve this answer|||||
  • This is basically just a brute force solution, and definitely not elegant. – sfdcfox Dec 24 '14 at 16:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.