DEV Community

Cover image for Important Regular Expression(REGEX) Patterns For Everyone
Arafat
Arafat

Posted on

Important Regular Expression(REGEX) Patterns For Everyone

Regex patterns are beneficial for validation because they allow you to define specific patterns for the data you want to match. In addition, they can be used to check for patterns that are difficult or impossible to check for using other methods.

However, regex patterns can be challenging to write and debug, so I've picked most of the valid regex patterns you can copy and paste into your next project.

Patterns

Matching a URL: /^((https?|ftp|file):\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$/

Matching a URL slug: /^[a-z0-9-]+$/

Matching an email address: /^[a-zA-Z0-9.! #$%&'+/=? ^_`{|}~-]+@[a-zA-Z0-9-]+(?:. [a-zA-Z0-9-]+)$/

Matching a password (Minimum eight and maximum 10 characters, at least one uppercase letter, one lowercase letter, one number and one special character:): /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,10}$/

Matching an username: /^[a-zA-Z0-9_-]{3,16}$/

Matchin a date(dd/mm/yyyy): /^(0?[1-9]|[12][0-9]|3[01])([ \/\-])(0?[1-9]|1[012])\2([0-9][0-9][0-9][0-9])(([ -])([0-1]?[0-9]|2[0-3]):[0-5]?[0-9]:[0-5]?[0-9])?$/

Matching time in 24 hour format: /^([01]?[0-9]|2[0-3]):[0-5][0-9]$/

Matching hex color code: /^#?([a-fA-F0-9]{6}|[a-fA-F0-9]{3})$/

Matching a phone number: /^\+?(\d.*){3,}$/

Matching an ID of Youtube channel: /https?:\/\/(www\.)?youtube.com\/channel\/UC([-_a-z0-9]{22})/i

Matching IPv4 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]?)$/


Conclusion

It's important to note that these regular expressions are just a starting point and may not match every valid URL, email address, or other patterns you want to reach. Therefore, you may need to modify or create regular expressions to meet your needs.

Top comments (1)

Collapse
 
randalschwartz profile image
Randal L. Schwartz

Many of these are overrestrictive. Most of those things have far more legal variety than the regex allows. For example....

No, please don't use this so-called "regex email validation".

I can think of a few email addresses that are perfectly valid that do not match that regex. When you want to validate an email address, please do not use a hand-rolled (or even copy-n-pasted) regex.

Instead, use (Dart) pub.dev/packages/email_validator (or Perl) metacpan.org/pod/Mail::RFC822::Add..., which properly implements the RFC822 (et. seq.) address according to the rules in the RFC.

(Jokingly...) Or, cut-n-paste this one (and only this one): ex-parrot.com/~pdw/Mail-RFC822-Add.... Don't forget to remove the newlines from that 1400-char monster. :)