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