Reputation: 86747
I'd like to regex that a value has no spaces (^[\S]*$
) and only contains letters (\w+
). But how do I combine these two to one regex?
Expected result should be:
oneword: true
one word: false
1word: false
Upvotes: 1
Views: 16177
Reputation:
Use \p{Alpha}
which is an alphabetic character:[\p{Lower}\p{Upper}]
With the above your regular expression will be \p{Alpha}+
, which matches one or more of alphabetic characters. This ignores digits, underscores, whitespaces etc.
For more info look at section POSIX character classes (US-ASCII only) in this document.
Upvotes: 1
Reputation: 11937
If you want a non-regex solution, perhaps you could try something like this:
public boolean valid(final String string){
for(final char c : string.toCharArray())
if(!Character.isLetterOrDigit(c))
return false;
return true;
}
Upvotes: 1
Reputation: 33908
I guess you may want something like (if the empty string is to be valid):
^[A-Za-z]*$
\w
contains digits and _
too, so that would match 1word
.
Upvotes: 9
Reputation: 369064
\w
not only match alphabets, but also match digits, underscore(_
). To match only alphabets, use:
^[A-Za-z]+$
Upvotes: 1
Reputation: 785128
For matching letters only this regex would be enough:
^[a-zA-Z]+$
\w
means letter, digits and underscoreUpvotes: 4