I’m trying to allow only certain words through a regexp filter in Java, i.e.:
Pattern p = Pattern.compile("^[a-zA-Z0-9\\s\\.-_]{1," + s.length() + "}$");
But I find that it allows through 140km/h because forward slash isn’t handled. Ideally, this word should not be allowed.
Can anyone suggest a fix to my current version?
I’m new to regexp and don’t particularly follow it fully yet.
The regexp is in a utils class method as follows:
public static boolean checkStringAlphaNumericChars(String s) {
s = s.trim();
if ((s == null) || (s.equals(""))) {
return false;
}
Pattern p = Pattern.compile("^[a-zA-Z0-9\\s\\.-_]{1," + s.length() + "}$");
// Pattern p = Pattern.compile("^[a-zA-Z0-9_\\s]{1," + s.length() + "}");
Matcher m = p.matcher(s);
if (m.matches()) {
return true;
}
else {
return false;
}
}
I want to allow strings with underscore, space, period, minus. And to ensure that strings with alpha numerics like 123.45 or -500.00 are accepted but where 5,000.00 is not.
You can just use
sis notnullwhen you try to do.matches()on it.\wto look for alphanumerics plus the underscore. tchrist will also be the first to point out this is more correct than[A-Za-z0-9_]+at the very end ensures you have at least one character (ie: the string is not empty)^and$since.matches()tries to match the pattern against the whole string ..) in a character class.New Demo: http://ideone.com/qraob