1

I want a regular expression that accepts as input characters (A..Z or a..z) and does not accept numbers and special characters. I wrote this method and these patterns but it doesn't work:

 public static Pattern patternString = Pattern.compile("\\D*"); public static Pattern special = Pattern.compile("[!@#$%&*,.()_+=|<>?{}\\[\\]~-]"); public static boolean checkString(String input) { boolean bool_string = patternString.matcher(input).matches(); boolean bool_special = !special.matcher(input).matches(); return (bool_string && bool_special); } 

checkString should return true if the input is: hello, table, Fire, BlaKc, etc.

checkString should return false if the input is: 10, tabl_e, +, hel/lo, etc.

How can I do that? Thank you

1

1 Answer 1

1

Use something like this:

if (subjectString.matches("[a-zA-Z]+")) { // It matched! } else { // nah, it didn't match... } 
  • no need to anchor the regex with ^ and $ because the matches method only looks for full matches
  • [a-zA-Z] is a character class that matches one character in the ranges a-z or A-Z
  • the + quantifier makes the engine match that one or more times
Sign up to request clarification or add additional context in comments.

Comments