Cord Awtry
Cord Awtry

Reputation: 93

Java RegEx not working as expected

Wondering if someone can tell me why this regular expression doesn't work.

Expression -> ^[A-Za-z0-9$&!#-_?:;\"']+$

The problem is, it's matching against characters not in the set. For example, the word match properly matches and the word match~ does not, but match@ and match! incorrectly match.

I'm using java to match it, and the matching should be fairly straight forward with the code below:

        RE re = new RE(expression);
        return re.match(value);

I know it's probably something ridiculously simple that I'm missing, but if anyone has any thoughts on it, I'd greatly appreciate it!

Upvotes: 1

Views: 320

Answers (2)

Bruno Silva
Bruno Silva

Reputation: 3097

The problem is the hyphen - in your character set. Your are accepting characters from # to _.

Change it to ^[-A-Za-z0-9$&!#_?:;\"']+$ or escape -.

Upvotes: 1

Dervall
Dervall

Reputation: 5744

I suspect its #-_ that is acting up. Escape the - and see if that helps.

New expression would be ^[A-Za-z0-9$&!#\-_?:;\"']+$

Upvotes: 2

Related Questions