Skip to content

Instantly share code, notes, and snippets.

@auxcoder
Forked from nerdsrescueme/regex.txt
Last active August 20, 2018 21:20
Show Gist options
  • Save auxcoder/c8ee455edeb31a0fb04f to your computer and use it in GitHub Desktop.
Save auxcoder/c8ee455edeb31a0fb04f to your computer and use it in GitHub Desktop.
Common Regex

Javascript Regex

Remove html tags

var regex = /(<([^>]+)>)/ig;
var htmlContent = "<p>test</p>";
var result = htmlContent.replace(regex, "");

console.log(result);

Matches start tag of specific tag including attibutes

var regex = /<\s*div.*?>/g;
var htmlContent = "<div class="tab1">tabs generator</div>";
var result = htmlContent.replace(regex, "");
// tabs generator</div>

Matches close part of specific tag pair

var regex = <\s*\/\s*div\s*.*?>;
var htmlContent = "<div class="tab1">tabs generator</div>";
var result = htmlContent.replace(regex, "");
// <div class="tab1">tabs generator

Match all start tags including attributes in the tags

var regex = /<\s*\w.*?>/g;
var htmlContent = "<div class="box">5 px radius of round corner</div><div class="box">7 px radius of round corner</div><div style="color:#6699cc">color</div>";
var result = htmlContent.replace(regex, "");
// 5 px radius of round corner</div>7 px radius of round corner</div>color</div>

Matches specific tag pairs and content between them

var regex = /<\s*h4[^>]*>(.*?)<\s*\/\s*h4>/g
var htmlContent = "<h4 class="sds">And more ...</h4>";
var result = htmlContent.replace(regex, "");
// empty string

Valid Email

var emails = ['admin@domain', 'admin@domain.c', 'admin@domain.co'];
var emailPattern = new RegExp('/^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/', 'i');
// we can use ng-pattern="emailPattern"

function testElement(element, index, array){
    console.log(emailPattern.test(element));
}
emails.forEach(testElement);
// false
// false
// true

Specific email rules

  • no dot at start of the string ^(?!\.)
  • no dot after a dot (?!.*\.{2})
  • no dot before (?<!\.)@
var emails = ['.admin@domain.com', 'ad..min@domain.com', 'admin.@domain.com'];
var emailPattern = new RegExp('/^(?!\.)(?!.*\.{2})[\w\d._%-]+(?<!\.)@[\w\d-.]{2,}\.[\w\d]{2,}$/', 'i');
function testElement(element, index, array){
    console.log(emailPattern.test(element));
}
emails.forEach(testElement);
// false
// false
// false

Valid Url

var urlPattern = https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*);
var url = "https://google.com"
console.log(urlPattern.test(url));

Simple url no matter how many segments and params or protocol (ftp, http, https).

var simpleUrlPattern = /^(ftp|http|https):\/\/[^ "]+$/
var url = "https://google.com"
console.log(simpleUrlPattern.test(url)); // true

Valid base64 image (png || jpg || gif)

var base64 = /^data:image\/(?:png|jpg|gif);base64,(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/
var data = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAmCAYAAACCjRgBAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAaRJREFUeNrUmdGNhCAQhtm7Bni8R0vYEixhS7AES6ADS7AESrAEtgNLoIQ7c8Fkbg6GAUVhkkmMoplP/n/AKIQQZsvvRtM83EGzAQEejdX+W/eHaDyOAAzIP8adu2UqUn0wE8aar647FWAA96gtpUsFzg81AxhQPA4F5FQtwD5eeq5JxvOkAzSBZ1QPoJAEm5JQt6VFpu9aMvHevRaX+/GlALlttAdjejQbr6sBchayxQO4z5rNMPRhAJEhO+vR/OquTbUCSFCkikjreSUAt5/vMlmJcTrD0IcBNNK/jLRNyh/ccacBjKj4EMSc8GZTDZ0N8AT3jEBKGAK3zZRFcioFAA2pPX6AEEvG9joFOgtAE4aEEJZom9xF0pwNMDLanUSLm8rsbhZI9BQArPsz2ivnZVGGZgOEdF86TMRDbADNWIhKRMzQLACO7kvGRBg6CpCi+5L7KBtoCCTAXbpP2cmSAHfpPvYtoTkAd+s+1sZ7CqAG3ccMvYYAatI9x9D/AGrTvS9eaK/1B6A23ccM7QUYRf3RwZqb/8X06XT11Wj97x8BBgAaVoUVrAA6gAAAAABJRU5ErkJggg=="

console.log(base64.test(data)); // true

Negative lookahead Regular Expression

Javascript has no support for look-behinds then lookahead.

var re = /^(?!.*foo\.html$).*\.html$/i;
var data = [
  'foo.html',
  'bar.html',
  'loo.html'
];
data.forEach(function(item) {
    console.log(re.test(item));
});
// false
// true
// true

Perl and PHP Regular Expressions

PHP regexes are based on the PCRE (Perl-Compatible Regular Expressions), so any regexp that works for one should be compatible with the other or any other language that makes use of the PCRE format. Here are some commonly needed regular expressions for both PHP and Perl. Each regex will be in string format and will include delimiters. All Major Credit Cards

This regular expression will validate all major credit cards: American Express (Amex), Discover, Mastercard, and Visa.

//All major credit cards regex
'/^(?:4[0-9]{12}(?:[0-9]{3})?|5[1-5][0-9]{14}|6011[0-9]{12}|622((12[6-9]|1[3-9][0-9])|([2-8][0-9][0-9])|(9(([0-1][0-9])|(2[0-5]))))[0-9]{10}|64[4-9][0-9]{13}|65[0-9]{14}|3(?:0[0-5]|[68][0-9])[0-9]{11}|3[47][0-9]{13})*$/'

Alpha-Numeric Characters

Test for alpha-numeric characters with this regexp.

//Alpha-numeric characters only
'/^[a-zA-Z0-9]*$/'

Alpha-Numeric Characters With Spaces

Test for alpha-numeric characters and spaces with this regexp.

//Alpha-numeric characters with spaces only
'/^[a-zA-Z0-9 ]*$/'

Alphabetic Characters

This regex will test for alphabetic characters only (upper and lowercase).

//Alphabetic characters only
'/^[a-zA-Z]*$/'

American Express Credit Card

Verify Amex credit cards with this regexp.

//Amex credit card regex
'/^(3[47][0-9]{13})*$/'

Australian Postal Codes

If you need to verify Australian Postal Codes, use this regular expression.

//Australian Postal Codes
'/^((0[289][0-9]{2})|([1345689][0-9]{3})|(2[0-8][0-9]{2})|(290[0-9])|(291[0-4])|(7[0-4][0-9]{2})|(7[8-9][0-9]{2}))*$/'

Canadian Postal Codes

Tests for valid Canadian Postal Codes.

//Canadian Postal Codes
'/^([ABCEGHJKLMNPRSTVXY][0-9][A-Z] [0-9][A-Z][0-9])*$/'

Canadian Provinces

Evaluate Canadian province abbreviations with this regular expression.

//Canadian Province Abbreviations
'/^(?:AB|BC|MB|N[BLTSU]|ON|PE|QC|SK|YT)*$/'

Date (MM/DD/YYYY)

Validate the calendar date in MM/DD/YYYY format with this regex. Optional separators are spaces, hyphens, forward slashes, and periods. The year is limited between 1900 and 2099.

//Date (MM/DD/YYYY)
'/^((0?[1-9]|1[012])[- /.](0?[1-9]|[12][0-9]|3[01])[- /.](19|20)?[0-9]{2})*$/'

Date (YYYY/MM/DD)

Validate the calendar date in YYYY/MM/DD format with this regex. Optional separators are spaces, hyphens, forward slashes, and periods. The year is limited between 1900 and 2099.

//Date (YYYY/MM/DD)
'#^((19|20)?[0-9]{2}[- /.](0?[1-9]|1[012])[- /.](0?[1-9]|[12][0-9]|3[01]))*$#'

Digits

This regex will test for digits (whole numbers).

//Digits only
'/^[0-9]*$/'

Diner's Club Credit Card

Test and verify Diner's Club credit card numbers with this regexp.

//Diner's Club credit card regex
'/^(3(?:0[0-5]|[68][0-9])[0-9]{11})*$/'

Emails

This email regex is not fully RFC5322-compliant, but it will validate most common email address formats correctly.

//Email regex
'/^([a-zA-Z0-9._%-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4})*$/'

IP Addresses

Test IP Addresses with this regular expression.

//IP address regex
'/^((?:(?: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]?))*$/'

Lowercase Alphabetic Characters

This regex will test for lowercase letters.

//Lowercase letters only
'/^([a-z])*$/'

MasterCard Credit Card

Verify MasterCard credit card numbers with this regex.

//MasterCard credit card numbers
'/^(5[1-5][0-9]{14})*$/'

Passwords

Test for a strong password with this regex. The password must contain one lowercase letter, one uppercase letter, one number, and be at least 6 characters long.

//Password regex
'/^(?=^.{6,}$)((?=.*[A-Za-z0-9])(?=.*[A-Z])(?=.*[a-z]))^.*$/'

Phone Numbers (North American)

This regex will validate a 10-digit North American telephone number. Separators are not required, but can include spaces, hyphens, or periods. Parentheses around the area code are also optional.

//Phone number regex
'/^((([0-9]{1})*[- .(]*([0-9]{3})[- .)]*[0-9]{3}[- .]*[0-9]{4})+)*$/'

Social Security Numbers

If you need to validate US Social Security Numbers, use this regular expression

//SSN regex
'/^([0-9]{3}[-]*[0-9]{2}[-]*[0-9]{4})*$/'

UK Postal Codes

This regexp verifies UK Postal Codes.

//UK Postal Codes regex
'/^([A-Z]{1,2}[0-9][A-Z0-9]? [0-9][ABD-HJLNP-UW-Z]{2})*$/'

Uppercase Alphabetic Characters

This regex will test for uppercase letters.

//Uppercase letters only
'/^([A-Z])*$/'

URLs

This URL regex will validate most common URL formats correctly.

//URL regex
'/^(((http|https|ftp):\/\/)?([[a-zA-Z0-9]\-\.])+(\.)([[a-zA-Z0-9]]){2,4}([[a-zA-Z0-9]\/+=%&_\.~?\-]*))*$/'

US States

Validate all 2-letter US State abbreviates with this regular expression.

//US States regex
'/^(?:A[KLRZ]|C[AOT]|D[CE]|FL|GA|HI|I[ADLN]|K[SY]|LA|M[ADEINOST]|N[CDEHJMVY]|O[HKR]|PA|RI|S[CD]|T[NX]|UT|V[AT]|W[AIVY])*$/'

US ZIP Codes

This regexp verifies US ZIP Codes, with an optional 4 number ZIP code extension.

//US ZIP Codes regex
'/^([0-9]{5}(?:-[0-9]{4})?)*$/'

Visa Credit Card

Verify Visa credit card numbers with this regex.

//Visa credit card numbers
'/^(4[0-9]{12}(?:[0-9]{3})?)*$/'

JavaScript Regular Expressions

The JavaScript version of regex is a slightly different flavor than the PCRE variety, so I've included those regexes in a separate section. All Major Credit Cards

This regular expression will validate all major credit cards: American Express (Amex), Discover, Mastercard, and Visa. Note that it is not quite as precise as its counterpart Perl and PHP regex.

//All major credit cards JavaScript regex
'^(?:4[0-9]{12}(?:[0-9]{3})?|5[1-5][0-9]{14}|6011[0-9]{12}|3(?:0[0-5]|[68][0-9])[0-9]{11}|3[47][0-9]{13})$'

Alpha-Numeric Characters

Test for alpha-numeric characters with this regexp.

//JavaScript alpha-numeric characters only
'^[a-zA-Z0-9]+$'

Alphabetic Characters

This regex will test for alphabetic characters only (upper and lowercase).

//JavaScript Alphabetic characters only
'^[a-zA-Z]+$'

Canadian Postal Codes

Tests for valid Canadian Postal Codes.

//JavaScript Canadian Postal Codes
'^[ABCEGHJKLMNPRSTVXY][0-9][A-Z] [0-9][A-Z][0-9]$'

Date (MM/DD/YYYY)

Validate the calendar date in MM/DD/YYYY format with this regex. Optional separators are spaces, hyphens, forward slashes, and periods. The year is limited between 1900 and 2099.

//JavaScript Date (MM/DD/YYYY)
'^(0?[1-9]|1[012])[- /.](0?[1-9]|[12][0-9]|3[01])[- /.](19|20)?[0-9]{2}$'

Date (YYYY/MM/DD)

Validate the calendar date in YYYY/MM/DD format with this regex. Optional separators are spaces, hyphens, forward slashes, and periods. The year is limited between 1900 and 2099.

//JavaScript Date (YYYY/MM/DD)
'^(19|20)?[0-9]{2}[- /.](0?[1-9]|1[012])[- /.](0?[1-9]|[12][0-9]|3[01])$'

Digits

This regex will test for digits (whole numbers).

//JavaScript digits only
'^[0-9]+$'

Emails

This email regex is not fully RFC5322-compliant, but it will validate most common email address formats correctly.

//JavaScript email regex
'^[a-zA-Z0-9._%-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$'

Passwords

Test for a strong password with this regex. The password must contain one lowercase letter, one uppercase letter, one number, and be at least 6 characters long.

//JavaScript Password regex
"(?=^.{6,}$)((?=.*[A-Za-z0-9])(?=.*[A-Z])(?=.*[a-z]))^.*"

Phone Numbers (North American)

This regex will validate a 10-digit North American telephone number. Separators are not required, but can include spaces, hyphens, or periods. Parentheses around the area code are also optional.

//JavaScript phone number regex
'^(([0-9]{1})*[- .(]*([0-9]{3})[- .)]*[0-9]{3}[- .]*[0-9]{4})+$'

URLs

This URL regex will validate most common URL formats correctly.

//JavaScript URL regex
'^((http|https|ftp)://)?([[a-zA-Z0-9]\-\.])+(\.)([[a-zA-Z0-9]]){2,4}([[a-zA-Z0-9]/+=%&_\.~?\-]*)$'

US ZIP Codes

This regexp verifies US ZIP Codes, with an optional 4 number ZIP code extension.

//JavaScript US ZIP Codes regex
'^[0-9]{5}(?:-[0-9]{4})?$'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment