aspose file tools
The moose likes Java in General and the fly likes How avoid replacement of new line char in regex string replacement? Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login
JavaRanch » Java Forums » Java » Java in General
Reply Bookmark "How avoid replacement of new line char in regex string replacement?" Watch "How avoid replacement of new line char in regex string replacement?" New topic
Author

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

Maulin Vasavada
Ranch Hand

Joined: Nov 04, 2001
Posts: 1865
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


1. Have fun @ http://faq.javaranch.com/java/JavaRaq
2. Looking for simple infix2postfix conversion and postfix evaluation package? Click here
Michael Dunn
Ranch Hand

Joined: Jun 09, 2003
Posts: 4632
these seem to work OK

s1 = s1.replaceAll("[^\\r\\n&&[\\s]]+",TOKEN);
or
s1 = s1.replaceAll("[ \\t\\x0B\\f]+",TOKEN);
Maulin Vasavada
Ranch Hand

Joined: Nov 04, 2001
Posts: 1865
Thanks Michael.

Second one seems more intuitive

Regards,
Maulin
 
I agree. Here's the link: http://zeroturnaround.com/jrebel - it saves me about five hours per week
 
subject: How avoid replacement of new line char in regex string replacement?
 
Similar Threads
Regular expression to search for words not beginning with a single quote and with or without spaces
Replace tokens in a file
Java regex search. ".*" macther.find() or matcher.replaceAll, give more matches than intended
Search for whitespace in a String
reverse position of String into a StringBuffer