Michael
Michael

Reputation: 42080

Regex to match ASCII non-alphanumeric characters

I need a regex to match ASCII non-alphanumeric characters. The regex should not match non-ASCII characters. I am using the following:

   "[\\u0000-\\u002f\\u003a-\\u0040\\u005b-\\u0060\\u007b-\\u007f]"

Can I simplify this regex ?

Upvotes: 4

Views: 1853

Answers (3)

Unihedron
Unihedron

Reputation: 11041

You can use a set intersection:

"[\\p{ASCII}&&[^\\p{Alnum}]]"

Read: Reference - What does this regex mean?

Upvotes: 2

anubhava
anubhava

Reputation: 785376

You can use this regex in Java

^(?=[^0-9a-zA-Z]+$)\p{ASCII}+$

OR else:

^(?!\p{Alnum}+$)\p{ASCII}+$

Upvotes: 2

Casimir et Hippolyte
Casimir et Hippolyte

Reputation: 89565

Yes you can use a character class intersection. Example:

[\\p{ASCII}&&\\P{Alnum}]

This means: intersection between all ascii characters and all non alphanumeric characters

Upvotes: 6

Related Questions