tags:

views:

84

answers:

4

I would like to show only a-z0-9 in a string, and the other characters should be replaced by null string

String s=this.saveFileName.replaceAll("/[a-z0-9. ]/", "");

This those not work, any ideas why?

+1  A: 

You don't need these / /.

Some languages like PHP expect you to place the regex between a pair of delimiters, Java does not.

Since you want to replace everything other than a-z0-9 you need the regex [^a-z0-9] or alternatively [^a-z\\d]

A [..] is a char class to match a char listed in it. The char class can also contain ranges like [a-z] which matches one lowercase letter. Now a ^ at the start of the char class negates it, so [^a-z] matches any one char other than a lower case letter.

codaddict
I think he's looking to preserve lowercase characters and numerals and strip out everything else. Your code strips out lowecase letters, numerals, periods, and spaces. The wording of the question was pretty bad though, so I can't be sure.
Mike Deck
@Mike: thanks for pointing.
codaddict
+1  A: 

Have you tried it without the // marks?

String s=this.saveFileName.replaceAll("[^a-z0-9]", "");
zigdon
+9  A: 

Try this:

String s = "abc123ABC!@#$%^;'xyz";
String newString = s.replaceAll("[^a-z0-9]", "");
//newString is now "abc123xyz"

This takes advantage of the negation (^) operator in character classes which basically says, "match everything except the following characters."

Also, you don't need slashes when defining Java regexes.

Mike Deck
Thanks. I wasn't aware there was a negation operator.
Rezler
A: 

This regex seems to do the trick :

String s="Testing-1.2.3_$".replaceAll("[^a-z0-9. ]", "");

output :

esting1.2.3

the ^ symbol negates the set and the slashes are not needed.

Peter Tillemans