Regular Expressions Tutorial: Learn Regex from Scratch
Regular expressions (regex) are a powerful tool for describing string matching patterns. Whether you are doing form validation, text searching, or data extraction, regex lets you accomplish complex text processing with concise syntax.
What Are Regular Expressions?
A regular expression is a pattern string composed of special and ordinary characters that describes a set of strings matching specific rules. First formulated by mathematician Stephen Kleene in the 1950s, regex has since become fundamental in computer science and programming.
Basic Syntax Elements
| Syntax | Description | Example | Matches |
|---|---|---|---|
. | Any single character | h.t | hat, hit, hot |
* | Previous char 0+ times | ab*c | ac, abc, abbc |
+ | Previous char 1+ times | ab+c | abc, abbc (not ac) |
? | Previous char 0 or 1 time | colou?r | color, colour |
^ | Start of string | ^Hello | Strings starting with Hello |
$ | End of string | world$ | Strings ending with world |
[abc] | Any char in brackets | [aeiou] | Any vowel |
Character Class Shorthands
| Shorthand | Equivalent | Description |
|---|---|---|
\d | [0-9] | Any digit |
\D | [^0-9] | Any non-digit |
\w | [A-Za-z0-9_] | Any word character |
\s | [ \t\n\r] | Any whitespace |
Learning Tip: The best way to learn regex is by practicing. Use our online testing tool to see match results in real-time, which dramatically accelerates the learning process.
Quantifiers
Quantifiers specify how many times the preceding element should repeat:
{n}— Exactly n times{n,}— At least n times{n,m}— Between n and m times
Grouping and Capturing
Parentheses () group parts of a regex into capture groups. They serve two purposes: treating multiple elements as a single unit for quantifiers, and extracting matched substrings.
Try Our Testing Tool
Use our regex tester to validate your patterns in real-time:
Try the Regex Tester Tool →Conclusion
Regular expressions are a fundamental skill every developer should master. While the syntax may seem cryptic at first, once mastered, regex becomes one of the most powerful text processing tools in your arsenal.
References
- IEEE. "POSIX.2 — Regular Expressions." IEEE Std 1003.2. https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap09.html
- Mozilla Developer Network. "Regular expressions." MDN Web Docs. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_expressions
- Friedl, J. "Mastering Regular Expressions." O'Reilly Media, 3rd Edition, 2006.