views:

584

answers:

5

I tried using this but didn't work-

return value.replaceAll("/[^A-Za-z0-9 ]/", "");
+2  A: 

Why did you put those / It shouldn't be there

Luno
Neither should the space at the end of the character class.
Andrew Duffy
He's probably used to programming in PHP.
William
Yea, in php it works..So I though in Java it's the same case. Damn!Thanks. :)
Alex Gomes
+2  A: 
return value.replaceAll("[^A-Za-z0-9 ]", "");

This will leave spaces intact. I assume that's what you want. Otherwise, remove the space from the regex.

erickson
A: 

Try

return value.replaceAll("[^A-Za-z0-9]", "");

or

return value.replaceAll("[\\W]|_", "");
Andrew Duffy
With underscores, `return value.replaceAll("\\W", "");`
erickson
Of course. Compilers are great at spotting that sort of thing.
Andrew Duffy
A: 

Java's regular expressions don't require you to put a forward-slash (/) or any other delimiter around the regex, as opposed to other languages like Perl, for example.

abyx
A: 

I made this method for creating filenames:

public static String safeChar(String input)
{
    char[] allowed = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-_".toCharArray();
    char[] charArray = input.toString().toCharArray();
    StringBuilder result = new StringBuilder();
    for (char c : charArray)
    {
        for (char a : allowed)
        {
            if(c==a) result.append(a);
        }
    }
    return result.toString();
}
zneo