Skip to content

Instantly share code, notes, and snippets.

@sagar-gavhane
Last active January 19, 2019 17:03
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sagar-gavhane/ea33cd532534bbef000244b3366e1264 to your computer and use it in GitHub Desktop.
Save sagar-gavhane/ea33cd532534bbef000244b3366e1264 to your computer and use it in GitHub Desktop.
Regular Expression for JavaScript
// Matching a ip address version 4
const IPV4_1 = /^(25[0-5]|2[0-4][0-9]|1?[0-9][0-9]{1,2})(\.(25[0-5]|2[0-4][0-9]|1?[0-9]{1,2})){3}$/;
const IPV4_2 = /^(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9])\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[0-9])$/;
const IPV4WithPort = /^((?:2[0-5]{2}|1\d{2}|[1-9]\d|[1-9])\.(?:(?:2[0-5]{2}|1\d{2}|[1-9]\d|\d)\.){2}(?:2[0-5]{2}|1\d{2}|[1-9]\d|\d)):(\d|[1-9]\d|[1-9]\d{2,3}|[1-5]\d{4}|6[0-4]\d{3}|654\d{2}|655[0-2]\d|6553[0-5])$/;
// Matching a ip address version 6
const IPV6_1 = /^([0-9a-f]|:){1,4}(:([0-9a-f]{0,4})*){1,7}$/i;
// Matching a Username
const username_1 = /^[a-z0-9_-]{5,16}$/;
const username_2 = /^[\w\.-]{5,20}$/;
// Matching a Password
const password = /^[a-z0-9_-]{6,18}$/;
// Matching a Hex Value
const hexValue = /^#?([a-f0-9]{6}|[a-f0-9]{3})$/;
// Matching a Slug
const slug = /^[a-z0-9-]+$/;
// Matching an Email
const emailAddress1 = /^[A-Za-z0-9](([_\.\-]?[a-zA-Z0-9]+)*)@([A-Za-z0-9]+)(([\.\-]?[a-zA-Z0-9]+)*)\.([A-Za-z]{2,})$/; // failed to validate underscore domain names eg.hello@worl_d.com
const emailAddress2 = /^([a-z0-9_\.-]+)@([\da-z\.-]+)\.([a-z\.]{2,6})$/; // failed to validate titlecase email address
// Matching a URL
const url1 = /^(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$/;
const url2 = /^((https?|ftp)\://((\[?(\d{1,3}\.){3}\d{1,3}\]?)|(([-a-zA-Z0-9]+\.)+[a-zA-Z]{2,4}))(\:\d+)?(/[-a-zA-Z0-9._?,'+&%$#=~\\]+)*/?)$/;
// Matching an HTML Tag
const htmlTag = /^<([a-z]+)([^<]+)*(?:>(.*)<\/\1>|\s+\/>)$/;
// Matching an Mobile Number
const mobileNumber = /^(?:(?:\+|0{0,2})91(\s*[\ -]\s*)?|[0]?)?[789]\d{9}|(\d[ -]?){10}\d$/; // valid for indian mobile numbers
// Reference
// 1. https://code.tutsplus.com/tutorials/8-regular-expressions-you-should-know--net-6149
// 2. https://stackoverflow.com/questions/3813195/regular-expression-for-indian-mobile-numbers
// 3. http://www.regexlib.com
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment