loading..

loading, please wait...
Mohit Aneja a.k.a CSSJockey

CSSJockey.com

Hello! I am Mohit Aneja, Designer and Developer based in India.
I believe in creating a Unique & Practical Web Presence not just html pages.
If you need some cool stuff, let's talk :)

Useful Regular Expressions in Programming

Today we are here to discuss, learn and share a few regular expressions used by many programmers across different programming platforms. The beauty of using these regular expressions is the freedom to use them with any programming language, provided, it involves strings interpolation, be it web applications or stand-alone applications. Moreover, once you have a good understanding of these regular expressions, you can modify them according to your needs and requirements.

What is Regular Expression?

Regular Expression is a type of sub language used with main stream programming languages like PHP, ASP, JAVA, and many more. As a matter of fact, it can be used with any programming language. You can think of regular expressions as wild cards on steroids. You are probably familiar with wild card notations such as *.txt to find all text files in a file manager.

The regular expression equivalent is . *.txt$.

What is its use?

Regular expression is used to match strings of text, such as particular characters, words, or patterns of characters, e.g., I wish to search a word which starts with the letter ā€˜c’ and is followed by O twice and can end with any alphabet or a numerical. I can use these regular expressions to get exact matches like cool, cook, cooked, cooking, cooper, cooperate, etc.

What’s in it for me?

Regular expressions are very useful as they involve interpolation with strings, numerical, alphabets and special symbols like $ @ % * etc. In my opinion no application can be built without using regular expressions in some way. There are many features and uses of regular expressions and we will proceed to discuss a few regular expressions that are a “Must Know” for any programmer. We shall tests these expressions in the following scenarios using PHP:

  1. Validating Username.
  2. Validating Password.
  3. Validating Email Address.
  4. Matching a URL.

Validate Username

// regular expression for validating username
$valid_username = "/^[a-z0-9_-]{3,16}$/";

// input from user through a textbox
$user = $_POST['user'];

// using ‘preg_match’ to validate user input against the expression.
if(preg_match($valid_username, $user)){
$message= "Username Valid! You may proceed.";
}else{
$message = "Inavlid Username.";
$message .= "Username should contain only alphabets, numbers, underscores or hyphens.";
$message .= "Should be between 3 to 16 characters long.";
}
php

In the above code the regular expression will look for a specific pattern of username which contains characters such as letters (a-z); number (0-9); an underscore or a hyphen. Later, it would verify that the username is minimum 3 characters long without exceeding the upper limit of 16 characters. This verification is performed by {3,16} expression. Then we will end the string by a ā€˜$’.

Live Demo

Validate a password

$valid_password = "/^[a-z0-9_-]{6,18}$/";
$pass = $_POST['pass'];
if(preg_match($valid_password, $pass)){
$message = "Valid Password. You may proceed.";
}else{
$message = "Invalid Password.";
$message .= "Password should contain only alphabets, numbers, underscore or hyphen.";
$message .= "Should be between 6 to 18 characters long.";
}
php

Password is almost similar to matching a username the only difference here is that we need minimum of 6 characters.

Live Demo

Validate an email

$valid_email = "/^([a-z0-9_.-]+)@([da-z.-]+).([a-z.]{2,6})$/ ";
$email = $_POST['email'];
if(preg_match($valid_email, $email)){
$message = "Valid Email. You may proceed.";
}else{
$message = "Please enter a Valid Email.";
}
php

This is one of the most common, widely used and important regular expression for validating an email address. This matches a string that has all the parts required for an e-mail address. To explain in detail, it will look for one or more lowercase letters, numbers, underscores, dots, or hyphens first followed by @ sign, next it will look up for a domain name which can consist of one or more lowercase letters, numbers, underscores, dots, or hyphens and then it would look for extension which would vary from 2 to 6 characters that can be country specific like .ca, .net, .uk, .com or .co.uk.

Live Demo

Regular expression to match a URL

$valid_url = "/^(https?://)?([da-z.-]+).([a-z.]{2,6})([/w .-]*)*/?$/";

$url= $_POST['url'];
if(preg_match($valid_url, $url)){
$message = "Valid URL. You may proceed.";
}else{
$message = "Please enter a Valid URL.";
}
php

This one compares the URL where it will first look for http://, https:// or check for it presence at all. Next it looks up the domain name which consists of one or more numbers, letters, dots, or hyphens followed by another dot then two to six letters or dots. The later section “?([da-z.-]+)” is optional files and directories. Then the inside part “.([a-z.]{2,6})([/w .-]*)” matches any number of forward slashes, letters, numbers, underscores, spaces, dots, or hyphens. Then we say that this group can be matched as many times as we want. Pretty much this allows multiple directories to be matched along with a file at the end. I have used the star instead of the question mark because the star says zero or more, not zero or one. If a question mark was to be used there, we could match only one file/directory. Then a trailing slash is matched, but it can be optional. Finally we end with the end of the line.

Live Demo

Stay tuned and updated for more useful regular expressions to come in future readings.

You may also like to read..

12 Comments on Useful Regular Expressions in Programming


  1. Mar 04, 2013 / Jatinder:
    please also tell me about the how to use regular Expression for Name 1. first name only 2. first name +last name(last name optional) 3 first name + last name (both Required) 3. no numeric value + special charactersthanks in advance Reply
  2. Jan 09, 2013 / Charles:
    I would like to point out that you pose a *considerable* security risk by promoting passwords regular expressions that limit the amount of characters a user can chose from.The more options a user has for characters in their password, the harder it would be to crack.Limiting Your characters to simply alphanumeric characters as well as characters like the dash and underscore, which have their own respective meanings, encourage users to use dictionary words or word combinations as passwords.There are plenty of rainbow tables out there so even if you encrypt your passwords before you store them in a database, your database of passwords will be easier to crack.For passwords you should simply check the *strlen* property of the variable holding your password. Reply
  3. Jul 12, 2010 / Aaron:
    Thanks! The examples were very useful. Cheers. Reply
  4. Jun 11, 2010 / Ameya:
    I have a query here. Can I use this code in JSP files? Actually I have a few JSF and JSP files and i have to validate email in both if them. Is there any restriction in using it with them? Otherwise, great work :) I just hope it solves my issue. Waiting for answer.Ameya Reply
  5. Feb 13, 2010 / Jon:
    I've been looking for this since I'm just a beginner with things like validation. Very useful indeed. Reply
  6. Feb 12, 2010 / Evee:
    Very useful for user input validation, thanks for the tip! Reply
  7. Feb 11, 2010 / cmswind:
    Thanks for the information. Regular expressions is really must for every programmers. Reply
  8. Jan 16, 2010 / nubok:
    I like your code Reply
    1. Jan 18, 2010 / CSSJockey:
      Thanks, I appreciate your time for the positive vibes. Reply
  9. Dec 09, 2009 / Rupak Dhiman:
    Thanks!!! Reply
  10. Dec 08, 2009 / Pankaj Gupta:
    Nice Information. Reply
  11. May 19, 2010 / CSSJockey:
    Thanks, I am glad you like what I do.. I don't get much time to write due to hectic schedule however will try my best to share whatever I can. Reply

Leave a Reply

Stay up-to-date

Get latest tutorials and articles directly in your email.

Subscribe in RSS Reader

Connect via Facebook

Follow me on Twitter

Visit our Google+ Profile

Connect via Skype

I keep my Skype open all day long while I work on my computer.
Feel free to ping me to start conversation.

I love good conversations!!
If you have some big ideas, suggestions, feedback,
or want to discuss your project give me a shout.

 
%d bloggers like this: