0

How do I validate if a text only contains alphabetic characters?

I think we can use Pattern.matches() but I don't know the regular expression for alphabetic characters.

tchrist
  • 78,834
  • 30
  • 123
  • 180
user1757703
  • 2,925
  • 6
  • 41
  • 62

2 Answers2

2

Use a category for alphabetics, combined with matches, and delimiters for the beginning and end of input text, as such:

String valid = "abc";
String invalid = "abc3";
Pattern pattern = Pattern.compile("^\\p{Alpha}+$"); // use \\p{L} for Unicode support
Matcher matcher = pattern.matcher(valid);
System.out.println(matcher.matches());
matcher = pattern.matcher(invalid);
System.out.println(matcher.matches());

Output:

true
false

Note: this also happens to prevent empty inputs. If you want to allow them, use a different quantifier than +, namely, *.

Finally, since you will use that against a java.awt.TextField, you can simply access its text with the method getText().

Mena
  • 47,782
  • 11
  • 87
  • 106
  • You need to use `(?U)` if you expect that to match non-ASCII alphabetics. – tchrist Aug 04 '13 at 17:42
  • @tchrist actually the `?U` flag is invalid. You're probably thinking of `?u`, and that wouldn't work with my solution either. But thanks for pointing Unicode support out, I've adapted my answer. – Mena Aug 04 '13 at 17:49
  • No, I’m thinking of `(?U)` from Java 7. Before then, Java regexes really didn’t work well with Unicode. – tchrist Aug 04 '13 at 17:55
2

It would be better if you used JFormattedTextField

here's more info in it: http://docs.oracle.com/javase/7/docs/api/javax/swing/JFormattedTextField.html

Akash
  • 4,956
  • 11
  • 42
  • 70