A string must not include spaces or special characters. Only a-z, A-Z, 0-9, the underscore, and the period characters are allowed.
How do I achieve this?
Update:
All the solutions posted worked for me.
Thanks everyone for helping out.
A string must not include spaces or special characters. Only a-z, A-Z, 0-9, the underscore, and the period characters are allowed.
How do I achieve this?
Update:
All the solutions posted worked for me.
Thanks everyone for helping out.
if (!myString.matches("^[a-zA-Z0-9._]*$")) {
// fail ...
}
or you can use the \w
character class (shorthand for [a-zA-Z_0-9]
)
if (!myString.matches("^[\\w.]*$")) {
// fail ...
}
You could simply delete all the characters that don't match the set [a-zA-Z0-9_.]
. Alternatively you could replace characters not in the set with a valid character (e.g. the underscore). Finally you could altogether reject any string that does not consist solely of characters in the permitted set.
A different solution:
text = text.replaceAll("[\\w.]", "");
It removes the unwanted characters instead of just detecting them.
From Sun's website:
\w A word character: [a-zA-Z_0-9]
I am certain by the time I finish typing this, you will have received you answer. So here is some genuine advice to go with it - Take the time (hour or so) to learn the basics of regular expressions.
You will be surprised how often they show up in solutions to 'real world' problems.
Great testing resource -> http://gskinner.com/RegExr/
You can either make a "all characters must be one of these" regular expression or simply ask if any of the characters you dislike are present at all and if so reject the string. I believe the latter will be the easiest to write and understand later.