0

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
  • and "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.

Pshemo
  • 113,402
  • 22
  • 170
  • 242
user1893354
  • 4,946
  • 11
  • 38
  • 74
  • Can't you do one that matches and put a `!` in front? Like `!stringVar.matches("[A-Za-z0-9]");` – AntonH Apr 10 '14 at 20:01
  • 1
    First of all you need to add `+` to match one or more `\p{Punct}`. Second thing: what about white spaces (they are not alphanumeric but are also not `\p{Punct}`), should they be matched or not? Also should characters that are alphabetic in other languages beside English like `źźć` be matched or not? – Pshemo Apr 10 '14 at 20:06
  • Thanks Pshemo adding the + seemed to work. What I meant was that if I could get an expression that matched on any alphanumeric character I could simply negate it and obtain the solution to my original question of matching on strings that have only non-alphanumeric characters. Also in my particular use case there should be no whitespace or other language characters. Thanks again. – user1893354 Apr 10 '14 at 20:18

5 Answers5

3

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.

Community
  • 1
  • 1
aliteralmind
  • 18,274
  • 16
  • 66
  • 102
2

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 *.

Pshemo
  • 113,402
  • 22
  • 170
  • 242
1

I would try

\W

or

\W*

with .matches

Here is the documentation -> Predefined Character Classes

Jonathan
  • 106
  • 2
  • 6
1

This should work.

"[^A-Za-z0-9]*"
wvdz
  • 15,266
  • 3
  • 43
  • 82
1

Doesn't simply

[^A-Za-z0-9]*

work?

James_D
  • 177,111
  • 13
  • 247
  • 290