This week's giveaway is in the Android forum.
We're giving away four copies of Android Security Essentials Live Lessons and have Godfrey Nolan on-line!
See this thread for details.
The moose likes Java in General and the fly likes Remove all control characters except \n & \r Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Remove all control characters except \n & \r" Watch "Remove all control characters except \n & \r" New topic
Author

Remove all control characters except \n & \r

Srikanth Madasu
Ranch Hand

Joined: Sep 10, 2008
Posts: 48

I have a requirement of removing all the control characters from a string except CarriageReturn (CR) and LineFeed (LF).

I know how to remove all the control characters:



But i now want retain CR & LF and remove all other control characters.
Any help is much appreciated.

Thanks in advance.
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19655
    
  18

The API of Pattern already tells you how to do this - if you know where to look. It's in the "Character classes" section: [a-z&&[^bc]]. In this case, it's [\\p{Cntrl}&&[^\r\n]]

Keep in mind that the results are... odd. The \r only returns the cursor position to the start of the same line on Windows, so this is the output:
As you see, the "hello" is overwriting the start of the line. At first, it will overwrite the "A" and part of the tab. After the pattern replacing, it will replace "A Thi".


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Remove all control characters except \n & \r
 
Similar Threads
Return Carriage Help
Definition of carriage return and line feed
BufferedReader, readLine() method, and the issue
? about cross platform compatibility
byte array