[SalesForce] Replacing multiple consecutive spaces with Pipe character

I need to replace multiple consecutive spaces with pipe character ,I tried various regular expression but i couldn't get the output .Can anyone give me solution for this

Best Answer

Try this:

String s = ' this is a    multiple spaces sample   ';
System.debug(s.replaceAll('\\s+','|'));

gives you this result: DEBUG||this|is|a|multiple|spaces|sample|

To replace ONLY when you have more than one space use this:

System.debug(s.replaceAll('[ ]{2,}','|'));

this returns :

DEBUG| this is a|multiple spaces sample|
12:08:18.174 (37342000)|CUMULATIVE_LIMIT_USAGE