Regular Expression template for web development

regularexpression.png

What is regular expression?

A regular expression is a special text string for describing a search pattern, mainly for use in pattern matching with strings, or string matching.

Regex quick reference

Sample Definition
[abc] A single character of: a, b, or c
[^abc] Any single character except: a, b, or c
[a-z] Any single character in the range a-z
[a-zA-Z] Any single character in the range a-z or A-Z
^ Start of line
$ End of line
\A Start of string
\z End of string
. Any single character
\s Any whitespace character
\S Any non-whitespace character
\d Any digit
\D Any non-digit
\w Any word character (letter, number, underscore)
\W Any non-word character
\b Any word boundary
(...) Capture everything enclosed
(a|b) a or b
a? Zero or one of a
a* Zero or more of a
a+ One or more of a
a{3} Exactly 3 of a
a{3,} 3 or more of a
a{3,6} Between 3 and 6 of a
options:
  • i case insensitive
  • m make dot match newlines
  • x ignore whitespace in regex
  • o perform #{...} substitutions only once
  • The Common regular expression template

    1. Email

    /\A[\w+\-.][email protected][a-z\d\-.]+\.[a-z]+\z/i
    
    1. Match email:
    1. Don't match email:

    2. Phone number

    /^(\+\d{1,2}\s)?\(?\d{3}\)?[\s.-]\d{3}[\s.-]\d{4}$/
    
    1. Match Phone number
    • 123-456-7890
    • (123) 456-7890
    • 123 456 7890
    • 123.456.7890
    • +91 (123) 456-7890

    3. HTTP Url

    /^(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$/
    
    1. Valid URL
    1. Invalid URL

    4. IP Address

    /^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/
    
    1. Valid IP
    • 192.168.100.1
    • 127.0.0.1
    • 0.0.0.0
    1. Invalid IP
    • 256.123.123.1
    • 192.168.122.
    • 192.168.122

    5. Username

    /^[a-z0-9_-]{3,32}$/i
    
    1. Valid username
    • Jame007
    • user_Name
    • like-you
    1. Invalid username
    • a hacker
    • me+
    • you&I

    6. Password

    /^([[email protected]*#]{6,15})$/
    
    1. Valid password
    1. Invalid password
    • Hello
    • My password
    • no-one-can-guess-my-passord

    7. File Extension

    ([^\s]+(\.(?i)(jpg|png|gif|bmp))$)
    
    1. Match file
    • picture.jpg
    • picture123.png
    • image.gif
    1. Don't match file
    • picture.txt
    • cat-photo.
    • no-image

    8. Time Format

    /([01]?[0-9]|2[0-3]):[0-5][0-9]/
    
    1. Match Time
    • 00:00
    • 22:00
    • 9:00
    1. Don't match time
    • 00:0
    • 24:00
    • 12:65

    9. Date Format (dd/mm/yyyy, dd-mm-yyyy)

    /^(\d\d)[-\/](\d\d)[-\/](\d\d(?:\d\d)?)$/
    
    1. Match date
    • 11-02-2015
    • 11/02/2015
    1. Date don't match
    • 12-Feb-1222
    • 2-1-15

    Try online: http://rubular.com/