Regex Cheatsheet

CasesRegex (Java)
Valid Phone formatWith Parenthese:
^((\(\d{3}\))|\d{3})[- .]?\d{3}[- .]?\d{4}$
Example: (988) 989-8899

With International Prefix:
^(\+\d{1,3}( )?)?((\(\d{3}\))|\d{3})[- .]?\d{3}[- .]?\d{4}$
Example: +111 (202) 555-0125

10 digits:
^(\d{3}[- .]?){2}\d{4}$
Example: 989 999 6789
Valid Email format Simplest:
^(.+)@(.+)$

RFC 5322:
^[a-zA-Z0-9_!#$%&’*+\/=?`{|}~^.-]+@[a-zA-Z0-9.-]+$

No leading, trailing, consecutive dots:
^[a-zA-Z0-9_!#$%&’+\/=?{|}~^-]+(?:\.[a-zA-Z0-9_!#$%&’*+\/=?{|}~^-]+)@[a-zA-Z0-9-]+(?:.[a-zA-Z0-9-]+)*$
Valid Money format^(?:(?![,0-9]{14})\d{1,3}(?:,\d{3})*(?:\.\d{1,2})?|(?![.0-9]{14})\d{1,3}(?:\.\d{3})*(?:\,\d{1,2})?)$
Example: 123,234,432.43 , 123.234.432,43
Valid ISO Date time format(\d{4}-\d{2}-\d{2})[A-Z]+(\d{2}:\d{2}:\d{2}).([0-9+-:]+)
Example: 2021-10-12T23:59:00+07:00
Valid URL^(https?|ftp|file):\/\/[-a-zA-Z0-9+&@#\/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#\/%=~_|]
Example: https://www.the-tech-lead.com
Strong password^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%^&+=])(?=\S+$).{8,}$

– A digit must occur at least once
– A lower case letter must occur at least once
– An upper case letter must occur at least once
– A special character must occur at least once
– No whitespace allowed in the entire string
– At least eight places
Valid IP v4^(([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(\.(?!$)|$)){4}$
Example: 192.168.0.1
Valid IP v6Standard format:
^(?:[0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}$
Example: 2001:0db8:85a3:0000:0000:8a2e:0370:7334

Hex Compressed format:
^((?:[0-9A-Fa-f]{1,4}(?::[0-9A-Fa-f]{1,4})*)?)::((?:[0-9A-Fa-f]{1,4}(?::[0-9A-Fa-f]{1,4})*)?)$
Example: 2001:0db8:85a3:0000::8a2e:0370:7334
Valid Domain name^(?!-)[A-Za-z0-9-]+([\-\.]{1}[a-z0-9]+)*\.[A-Za-z]{2,6}$
Example: the-tech-lead.com
Valid Credit Card Number^(?:4[0-9]{12}(?:[0-9]{3})?|[25][1-7][0-9]{14}|6(?:011|5[0-9][0-9])[0-9]{12}|3[47][0-9]{13}|3(?:0[0-5]|[68][0-9])[0-9]{11}|(?:2131|1800|35\d{3})\d{11})$

for Visa, MasterCard, American Express, Diners Club, Discover, and JCB cards.
Frequently used regular expressions

Note:

  • when use String regex = "copied regex", don’t forget to add extra "\" , so "\d" should become "\\d" , "\." become "\\.", etc
  • Replace ^ and $ as .* to have the “containing” matching. Example to match a string containing texts look like money :
    Boolean match = someString.match(".*(?:(?![,0-9]{14})\\d{1,3}(?:,\\d{3})*(?:\\.\\d{1,2})?|(?![.0-9]{14})\\d{1,3}(?:\\.\\d{3})*(?:\\,\\d{1,2})?).*")

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s