Regex cookbook — Top 10 Most wanted regex

The most commonly used (and most wanted) regexes

UPDATED 5/15/19! After some time I thought about publishing this article (see my previous tutorial) with the regex I used most in the projects on which I was involved.

Write in the comments any regex that you would like to add and I will try (if I can) to implement them 😅

Happy coding!!!


Trim spaces — try it!

Matches text avoiding additional spaces

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

HTML Tag — try it!

Matches any valid HTML tag and the corresponding closing tag

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

Hexadecimal value — try it!

Matches any valid hex color inside text

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

Valid email (RFC5322) — try it!

Matches any valid email inside text

\b[\w.!#$%&’*+\/=?^`{|}~-]+@[\w-]+(?:\.[\w-]+)*\b

Username (simple) — try it!

Minimum length of 3, maximum length of 16, composed by letters, numbers or dashes.

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

Strong password — try it!

Minimum length of 6, 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])(?=.*[|!"$%&\/\(\)\?\^\'\\\+\-\*]))^.*

URL (http, https or ftp) — try it!

If you want to use capturing groups to get scheme, path, etc. (or add user-info, host, port…) feel free to ask it in comments!

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

IPv4 address — try it!

Matches any valid IPv4 address inside text

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

“Defanged” URL or IPv4 address — try it!

^(((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\/+=%&_\.~?\-]*)$

SSN — Social Security Number (simple) — try it!

If you want to check the validity of an SSN feel free to ask in comments!

^((?<area>[\d]{3})[-][\d]{2}[-][\d]{4})$

Alpha-numeric, literals, digits, lowercase, uppercase chars only

\w                //alpha-numeric only
[a-zA-Z] //literals only
\d
//digits only
[a-z]
//lowercase literal only
[A-Z]
//uppercase literal only

Have fun and do not forget to recommend the article if you liked it 💚

Do not forget to check out my previous article about regex tutorial!