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|`