lacas
lacas

Reputation: 14066

java replace regex a-z0-9 only

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?

Upvotes: 4

Views: 8515

Answers (4)

codaddict
codaddict

Reputation: 455000

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.

Upvotes: 2

Peter Tillemans
Peter Tillemans

Reputation: 35331

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.

Upvotes: 0

Mike Deck
Mike Deck

Reputation: 18397

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.

Upvotes: 14

zigdon
zigdon

Reputation: 15063

Have you tried it without the // marks?

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

Upvotes: 1

Related Questions