Reputation: 5938
I'm trying to come up with a regex expression that matches a string that has only non-alphanumic characters.
For example:
".."
would be true
".dds!f"
would be false
"sdjhgfsjd"
would be false
.I have tried str.matches("\\p{Punct}")
however this only seems to match single punctionation characters. eg. ".".matches("\\p{Punct}")
would be true but "..".matches("\\p{Punct}")
would be false.
I suppose an equivalent question would also be to match if there is any alphanumeric character in the string.
Upvotes: 0
Views: 843
Reputation: 106
I would try
\W
or
\W*
with .matches
Here is the documentation -> Predefined Character Classes
Upvotes: 1
Reputation: 124225
It seems that you can use
str.matches("\\P{Alnum}")
Alnum
is shorter form of alphabetic and numeric. Also \P{Alnum}
is negation of \p{Alnum}
. So this regex will return true if string contains only one or more characters which are not alphanumeric. If you want to also accept empty strings change +
to *
.
Upvotes: 2
Reputation: 20163
This matches strings containing no letters or digits:
^[^a-zA-Z0-9]*$
And this matches strings with at least one letter or digit:
^.*[a-zA-Z0-9].*$
Please take a look through the Stack Overflow Regular Expressions FAQ for some more helpful information.
Upvotes: 3