• Post Reply Bookmark Topic Watch Topic
  • New Topic

How avoid replacement of new line char in regex string replacement?  RSS feed

 
Maulin Vasavada
Ranch Hand
Posts: 1873
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all,

I have the following code,


Here the problem is, "\\s+" pattern matches the newlines in the string and replace them with TOKEN. I want every multiple occurance of whitespace chars to be replaced by TOKEN except for newline chars. How can I do that via some regex pattern only?

Alternatively I have to go long way to,
1. first replace all new line with a known token- say TOKEN1 to prevent them from getting replaced via "\\s+" pattern matching.
2. then match "\\s+" pattern and replace all multiple whitespace occurances with single space
3. replace all TOKEN1 back to newline.

Is there any other way via regex pattern we can do this? OR I have to go this long way I mention above?

Regards,
Maulin
 
Michael Dunn
Ranch Hand
Posts: 4632
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
these seem to work OK

s1 = s1.replaceAll("[^\\r\\n&&[\\s]]+",TOKEN);
or
s1 = s1.replaceAll("[ \\t\\x0B\\f]+",TOKEN);
 
Maulin Vasavada
Ranch Hand
Posts: 1873
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Michael.

Second one seems more intuitive

Regards,
Maulin
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!