8

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?

2 Answers 2

7

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

Example

// 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]');
system.debug(formatted);

Output

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

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
chars.remove(0);
String result ='';

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

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .