Writing a simple regex, but I’ve never been very good at this.
What I’m trying to do is check a string (filename) to make sure it only contains a-z, A-Z, 0-9 or the special characters underscore (_) period (.) or dash (-).
Here’s what I have
if(filename.length() < 1 || !filename.matches("^[a-zA-Z0-9[.][_][-]]+"))
return false;
else
return true;
This appears to work, but does not look very elegant to me. Is there a better / more readable way to write this?
Thanks in advance! Just trying to learn how to write these buggers better.
-Will
You don’t need to use
[]inside character class.So, you can write:
Also, you can use
\\winstead ofa-zA-Z0-9_.So, the regexp would be:
Also, this regexp will match a string like
StackOverflow 22.10$$2011by consumingStackOverflow 22.10. If you need your string to consist completely of those character, you should end the pattern with$– the end of the string: