0

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.

3 Answers 3

3

\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

Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.