Vyacheslav  Martynenko
Vyacheslav Martynenko

Reputation: 327

Java String character Pattern

How to check if string consists of letters only by using regular expression.
I know how to check only one character: if (s.matches("\\w")) System.out.println(true);
But I don`t understand how to check full string.

Upvotes: 0

Views: 614

Answers (3)

Reimeus
Reimeus

Reputation: 159754

\w includes numbers in its expression. You could do

if (s.matches("[a-zA-Z]*")) {
  ...
}

where * matches 0 or more characters. Note that empty strings are matched by this pattern also so you may want to use the + quantifier instead

Upvotes: 3

npinti
npinti

Reputation: 52185

Replace matches("\\w") with matches("^[A-Za-z]*$"). This should instruct the matcher to expect the string to be made up entirely of 0 or more letters (case insensitive).

The * denotes zero or more repetitions of what preceeds it. On the other hand, the + expects at least one instance of whatever it is that preceeds it, thus, the * operator can potentially match an empty string, which I do not know if it is something which you are after.

Upvotes: 2

rageandqq
rageandqq

Reputation: 2281

You can use regex matching [a-zA-Z] instead, of looking for the single character w, and add the + to specify you want all characters.

Something like:

System.out.println(s1.matches("[a-zA-Z]+"));

should do the trick.

Upvotes: 0

Related Questions