How to Write Regular Expressions
Regular expressions (regex) are a powerful tool for searching, validating, and manipulating text. While they have a reputation for being cryptic, learning the fundamentals makes regex an invaluable skill for any developer. This guide teaches you regex from the ground up with practical examples.
What Is a Regular Expression?
A regular expression is a sequence of characters that defines a search pattern. You can use it to find, match, or replace text in strings. Regex is supported in virtually every programming language and is built into tools like grep, sed, and most text editors.
Core Building Blocks
. → Any character (except newline)
\d → Digit (0-9)
\w → Word character (a-z, A-Z, 0-9, _)
\s → Whitespace
^ → Start of string
$ → End of string
* → Zero or more
+ → One or more
? → Zero or one
{n} → Exactly n times
{n,m} → Between n and m times
[abc] → Character set (a, b, or c)
[^abc] → Negated set (not a, b, or c)
(ab) → Capture group
a|b → Alternation (a or b)Practical Examples
- Match an email:
^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$ - Match a phone number:
^\\d3-\\d3-\\d4$ - Match a URL:
^https?://[^\\s]+$ - Match a date (YYYY-MM-DD):
^\\d4-\\d2-\\d2$
How to Write and Test a Regex
- 1Identify the pattern. Write down what you want to match in plain English first, then convert it to regex syntax.
- 2Test iteratively. Use the ToolStack Regex Tester to test your pattern against sample strings and refine it.
- 3Edge cases. Test with empty strings, very long strings, and special characters to ensure your pattern handles all inputs.
Try It: Test Your Regex Online
Use our free Regex Tester to test patterns against live input. See matches highlighted in real time.
Open Regex Tester