how To change my regex to reject underscores

monkey123 :

Currently have this regex string in my java code:

^[\\w\\-\\ \\#\\.\\/]{0,70}$

It successfully accepts those characters, however it also accepts underscore, how can modify the regex to reject underscore appearing anywhere in the string?

anubhava :

Your regex is:

^[\\w\\-\\ \\#\\.\\/]{0,70}$

It is using \w which is equivalent of [a-zA-Z0-9_], hence it allows underscore also.

You can change your character class to this:

^[-#. a-zA-Z0-9\\/]{0,70}$

Note that space, dot, #, / don't need to be escaped inside [...] and - if placed at first or last position doesn't require escaping either.

Guess you like