This week's book giveaway is in the Cloud/Virtualizaton forum.
We're giving away four copies of Mesos in Action and have Roger Ignazio on-line!
See this thread for details.
Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Regex for replacing special characters

 
sangeeta kapoor
Ranch Hand
Posts: 70
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 76
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This will replace all the special characters except dot (.)

String newName = name.replaceAll("[\\W]&&[^.]","_");
 
sangeeta kapoor
Ranch Hand
Posts: 70
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 262
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 1970
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic