Regex Cheatsheet
Regular expressions (regex) are patterns used for string matching and manipulation. Hereβs a quick reference guide for common regex syntax:
Basics
.: Matches any character except a newline.^: Matches the start of a string or line.$: Matches the end of a string or line.
Character Classes
[abc]: Matches any charactera,b, orc.[^abc]: Matches any character excepta,b, orc.[a-z]: Matches any lowercase letter.[A-Z]: Matches any uppercase letter.[0-9]: Matches any digit.[a-zA-Z0-9]: Matches any alphanumeric character.\d: Matches any digit (short for[0-9]).\w: Matches any word character (alphanumeric + underscore).\s: Matches any whitespace character (space, tab, newline).
Quantifiers
*: Matches the preceding element zero or more times.+: Matches the preceding element one or more times.?: Matches the preceding element zero or one time.{n}: Matches the preceding element exactlyntimes.{n,}: Matches the preceding elementnor more times.{n,m}: Matches the preceding element betweennandmtimes.
Groups and Alternation
(abc): Matches the groupabcand captures it.(?:abc): Matches the groupabcwithout capturing it.a|b: Matches eitheraorb.
Anchors
\b: Matches a word boundary.\B: Matches a position that is not a word boundary.(?=...): Positive lookahead assertion.(?!...): Negative lookahead assertion.
Escaping Special Characters
\\: Escapes a special character (e.g.,\\.matches a literal period).
Flags (Depends on Language)
i: Case-insensitive matching.g: Global match (find all occurrences).m: Multiline mode (^ and $ match the start/end of each line).s: Dot matches all, including newlines.u: Treat the pattern and input as UTF-16 or UTF-32.x: Ignore whitespace and allow comments.
Examples
/\d{3}-\d{2}-\d{4}/: Matches a standard US social security number./^[A-Za-z]+$/: Matches a string containing only letters./https?:\/\/(www\.)?\w+\.\w+/: Matches URLs starting withhttp://orhttps://./(\d+)\s?-\s?\1/: Matches repeated numbers separated by a hyphen.^(\/[^\/?]+)(\/[^\/?]+)?(\/[^\/?]+)?: Match all text up to the 3rd β/β in a URL^[a-z][a-z0-9+\-.]*://([a-z0-9\-._~%!$&'()*+,;=]+@)?([a-z0-9\-._~%]+|\[[a-z0-9\-._~%!$&'()*+,;=:]+\]): extract hostname from URL^https?:\/\/(.*)(\/[^\/?]+)(\/[^\/?]+)?(\/[^\/?]+)?: Match protocol (http/s), hostname, and path (3 forward slashes)
Useful links
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_expressions/Cheatsheet