regex with some special characters allowed

Advertisements

I want regex with following conditions:

  • As first character only A-Za-z is allowed.

  • After first character the following is allowed: A-Z a-z 0-9 and the special characters .-_/

I wrote this regex:

^[A-Za-z][A-Za-z0-9.-_\/]+$

But this allows also different special characters like : ? ! which is wrong.

I hope somebody can help me

Thanks in advance 🙂

>Solution :

It is due to the -, which denotes a range. Use the following with - escaped:

Pattern p = Pattern.compile( "^[A-Za-z][A-Za-z0-9.\\-_/]+$" );

Example inputs and results:

Input Matched?
A102? false
A102\ false
A102?_- false
A102. true
A102/ true
A102/-- true
A102_ true
A102/-_ true
A102.-_/ true
A1020 true

Leave a ReplyCancel reply