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 Delete Special Charecters form the String 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 "Delete Special Charecters form the String" Watch "Delete Special Charecters form the String" New topic
Author

Delete Special Charecters form the String

Saathvik Reddy
Ranch Hand

Joined: Jun 03, 2005
Posts: 228
Hi,

I have a String s1 = "abc@!&def(*)";
I want to delete all the special charecters from the String s1.
The expected result should be s1 = "abcdef"

How can i achive this?

Thanks,
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19656
    
  18

s1.replaceAll("[^\\w]", "")

This will look for all substrings matching the regular expression "[^\w]" which means everything except a word character (0-9, a-z, A-Z and _), and then replace them with the empty string.

If you thing that a word character is still too lenient, you can use "[^a-zA-Z0-9]", or even "[^a-zA-Z]".


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
Saathvik Reddy
Ranch Hand

Joined: Jun 03, 2005
Posts: 228
Rob,

Thanks a lot. It worked like charm!
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Delete Special Charecters form the String
 
Similar Threads
Problem in handling special chars
Japanese special charecters?
String question
Special charecters in URL
Unicode charecters