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

PiotrWolkowski
  • 8,408
  • 6
  • 48
  • 68
  • this post i think is the answer for u http://stackoverflow.com/questions/3617797/regex-to-match-only-letters – eldjon Jul 05 '14 at 21:17

1 Answers1

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
zx81
  • 41,100
  • 9
  • 89
  • 105