Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validate nickname with regex

I neet to validate a nick name without @ and #and it can't start with numbers

thi is my solution but the @ and #

(^[^0-9])([\w a-z A-Z 0-9][^@#])

.test:

andrea //true
0andrea // false

// these are true but I need them to be false

and@rea // true
and#rea // true
like image 260
jay Avatar asked Dec 25 '22 11:12

jay


2 Answers

your regex:

^(^[^0-9])([\w a-z A-Z 0-9][^@#])$

explained

  1. dont start with a number.start with any thing other than numbers.

  2. two letter upper/lower case or digit or underscore followed by any of ^@#

SO according to your regex, any three letter word will be matched.

use this:

^[^0-9]\w+$

this will work for usernames not conatining any special chars.

If you specifically just not want @ and #. use this :

^[^0-9][^@#]+$

demo here : https://regex101.com/r/gV9eO0/1

like image 184
aelor Avatar answered Jan 05 '23 17:01

aelor


I neet to validate a nick name without @ and # and it can't start with numbers

Using (!?pattern) is a negative lookahead so you can prevent a \d as first char without preventing the rest of the expression from looking at it, then

If you're only blacklisting then

^(?!\d)[^@#]+$

reg1

Otherwise, use a whitelist

^(?!\d)[a-zA-z\d ]+$

reg2

Notice how we keep matching to the end of the string, $.
I've used + because you probably don't want to permit zero-length nicknames.

Also, you can sort-of go down the route you were attempting by using a * or + operator on a group;

^(?!\d)(?:(?![@#])[a-zA-Z\d ])+$

reg3

Graphical representations via debuggex.com

like image 30
Paul S. Avatar answered Jan 05 '23 17:01

Paul S.