0

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

1 Answer 1

3

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
6
  • I tried this long back ...I need to remove only multiple consecutive spaces with a pipe character ...not the single space i.e. 'this is a|multiple spaces sample' Commented Mar 12, 2014 at 10:58
  • i updated my answer Commented Mar 12, 2014 at 11:10
  • It worked ...thank you.Can you give me some links to study about how to create regular expressions if u can.. Commented Mar 12, 2014 at 11:15
  • Uff, That is a really tough and large topic, start here en.wikipedia.org/wiki/Regular_expression Commented Mar 12, 2014 at 11:19
  • i want one more help from you...I need to replace all special characters except those between strings o tried this [^\\w\'] ..but it is replacing special characters between the quotes Commented Mar 17, 2014 at 10:48

You must log in to answer this question.

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