wood burning stoves 2.0*
The moose likes Beginning Java and the fly likes Regex for replacing special characters Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Regex for replacing special characters" Watch "Regex for replacing special characters" New topic
Author

Regex for replacing special characters

sangeeta kapoor
Ranch Hand

Joined: Jun 15, 2004
Posts: 70
String name= "12E463~1.jpg";
String newName = name.replaceAll("[a-zA-Z1-90_\\- \\.]*","_");

String name has some value which contains some special characters. I want all characters apart from
A-Z
a-z
0-9
. (dot)
_ (underscore)
- (hyphen)
to be replaced with an _ (underscore)

So I should get
12E463_1.jpg in newName

But using the above regex the opposite happens. All characters apart from the special character (~ in this case) gets replaced. Please tell me how to do the opposite of the above regex.

This does not work

String newName = name.replaceAll("[^a-zA-Z1-90_\\- \\.]*","_");
Srikanth Ramu
Ranch Hand

Joined: Feb 20, 2007
Posts: 76
This will replace all the special characters except dot (.)

String newName = name.replaceAll("[\\W]&&[^.]","_");
sangeeta kapoor
Ranch Hand

Joined: Jun 15, 2004
Posts: 70
Originally posted by srikanth ramu:
This will replace all the special characters except dot (.)

String newName = name.replaceAll("[\\W]&&[^.]","_");


Thanks for replying. But I want all the characters apart from

A-Z
a-z
0-9
. (dot)
_ (underscore)
- (hyphen)
to be replaced with an _ (underscore)
Alan Moore
Ranch Hand

Joined: May 06, 2004
Posts: 262
To invert a character class, add '^' to the beginning of it: Also, you want to use the + (one or more) quantifier instead of * (zero or more). Otherwise, you end up inserting an underscore at every other position.
Peter Chase
Ranch Hand

Joined: Oct 30, 2001
Posts: 1970
I'm not sure you need a + either.

If you use a +, you will replace each sequence of special characters with a single underscore. If you omit the + (and don't use * either), you will replace each individual special character with an underscore. Depends which result you want.
[ March 20, 2007: Message edited by: Peter Chase ]

Betty Rubble? Well, I would go with Betty... but I'd be thinking of Wilma.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Regex for replacing special characters
 
Similar Threads
Validating the file path using regex
Naming Conventions
regular pattern
Regex problem
Regular expression - help