Regex Example: Username Checker

Problem: Check following condition on a username

  • Can contain alphanumeric number and underscore
  • Must not start with a digit
  • Can have length from 8 to 30 characters

Solution:

Lets generate pattern one by one. Start by checking first character of username which should not be a digit so we have to use range to check start of string.

^([a-zA-Z]) this will check first character of string should be in either in uppercase or lowercase. If you have condition of having uppercase as start of string we have to use like this ^[A-Z].

Now after first character it can have alphanumerc or underscore so we have to use w.Now our expression become like this ^[a-z][A-Z]w (This is relative to Java that’s why i am using double slash).

Now as we have length condition also we have to apply for that also. TO checking first character we have applied regex now left length of string is from 7 to 29 which we app to w using {n,m} now regex become like this  ^[a-zA-Z]w{7,29} . As our pattern is ready we have to apply end of line.

Actual Pattern of username is  : ^[a-zA-Z]w{7,29}$

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Create a website or blog at WordPress.com

Up ↑

%d bloggers like this: