• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

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

 
Ranch Hand
Posts: 1873
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Ranch Hand
Posts: 4632
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks Michael.

Second one seems more intuitive

Regards,
Maulin
 
sunglasses are a type of coolness prosthetic. Check out the sunglasses on this tiny ad:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic