Useful Regex for your daily life

2020-05-28

post-thumb

Contents

Regex used in Brazil

CPF

Validates both 123.456.789-00 and 12345678900

Does not validate the algorithm, only the format

(^\d{3}\.\d{3}\.\d{3}\-\d{2}$)

CNPJ

Validates both 12.345.678/0001-00 and 12345678000100

Does not validate the algorithm, only the format

(^\d{2}\.\d{3}\.\d{3}\/\d{4}\-\d{2}$)

CPF or CNPJ

Very useful when you only need a valid document

(^\d{3}\.\d{3}\.\d{3}\-\d{2}$)|(^\d{2}\.\d{3}\.\d{3}\/\d{4}\-\d{2}$)

RG

Validates any RG, including endings with digit X

(^\d{1,2}).?(\d{3}).?(\d{3})-?(\d{1}|X|x$)

Phone

Validates any phone or mobile, with or without area code. The dash is optional.

(^[0-9]{2})?(\s|-)?(9?[0-9]{4})-?([0-9]{4}$)

ZIP Code (CEP)

Validates any ZIP code with the dash being optional.

(^[0-9]{5})-?([0-9]{3}$)

Others

Trim spaces

Who needs spaces, right?

^[\s]*(.*?)[\s]*$

HTML Tag

You’re doing scraping, I know it, this regex helps you with that

<([a-z]+)([^<]+)*(?:>(.*)<\/\1>|\s+\/>)

Hexadecimal value

\B#(?:[a-fA-F0–9]{6}|[a-fA-F0–9]{3})\b

Valid email

The best expression is at emailregex.com

When in doubt, always use the most current one from that site.

(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?: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]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])

Username

Any username, between 3 and 15 characters with letters, numbers, underscore and dash

/^[a-z0-9_-]{3,15}$/

Password

Password with at least 6 characters, at least one uppercase letter, at least one lowercase letter, at least one number, at least one special character

(?=^.{6,}$)((?=.*\w)(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*[|!"$%&\/\(\)\?\^\'\\\+\-\*]))^.*

URLs

Any valid http, https, ftp url

^(((https?|ftp):\/\/)?([\w\-\.])+(\.)([\w]){2,4}([\w\/+=%&_\.~?\-]*))*$

IPv4

Any valid IPv4

\b(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\b

URLs or IPv4

The 2 regex above combined

^(((h..ps?|f.p):\/\/)?(?:([\w\-\.])+(\[?\.\]?)([\w]){2,4}|(?:(?:25[0–5]|2[0–4]\d|[01]?\d\d?)\[?\.\]?){3}(?:25[0–5]|2[0–4]\d|[01]?\d\d?)))*([\w\/+=%&_\.~?\-]*)$

Regexes are powerful

You can do almost anything with regex, if you prefer to learn instead of just using them, I wrote an article that can help you: How to be happy using Regex

See you soon