user1893354
user1893354

Reputation: 5938

Regex match if String has no alphanumic characters

I'm trying to come up with a regex expression that matches a string that has only non-alphanumic characters.

For example:

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

Answers (5)

Jonathan
Jonathan

Reputation: 106

I would try

\W

or

\W*

with .matches

Here is the documentation -> Predefined Character Classes

Upvotes: 1

Pshemo
Pshemo

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

aliteralmind
aliteralmind

Reputation: 20163

This matches strings containing no letters or digits:

^[^a-zA-Z0-9]*$

Regular expression visualization

Debuggex Demo

And this matches strings with at least one letter or digit:

^.*[a-zA-Z0-9].*$

Regular expression visualization

Debuggex Demo

Please take a look through the Stack Overflow Regular Expressions FAQ for some more helpful information.

Upvotes: 3

wvdz
wvdz

Reputation: 16641

This should work.

"[^A-Za-z0-9]*"

Upvotes: 1

James_D
James_D

Reputation: 209358

Doesn't simply

[^A-Za-z0-9]*

work?

Upvotes: 1

Related Questions