Regular expressions (regex) are a powerful tool for searching and processing text. They may seem complex, but the basic concepts are quite simple. This guide will help you get started.
What are Regular Expressions?
A regular expression is a pattern for searching text. For instance, the expression \d{3}-\d{2}-\d{2} will find all phone numbers in the format 123-45-67.
Basic Syntax
Characters
.β any single character\dβ a digit (0-9)\wβ a letter, digit, or underscore\sβ a whitespace character (space, tab)[abc]β one of the characters a, b, or c[^abc]β any character except a, b, c
Quantifiers
*β 0 or more repetitions+β 1 or more repetitions?β 0 or 1 repetition{3}β exactly 3 repetitions{2,5}β from 2 to 5 repetitions
Anchors
^β start of a line$β end of a line\bβ word boundary
Practical Examples
Email Validation
^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$Phone (Ukraine)
^\+?380\d{9}$URL Address
^https?:\/\/[-\w.]+\.[a-z]{2,}(\/\S*)?$IP Address (IPv4)
^(\d{1,3}\.){3}\d{1,3}$Date (DD.MM.YYYY)
^(0[1-9]|[12]\d|3[01])\.(0[1-9]|1[0-2])\.\d{4}$Testing Regular Expressions
Use Regex Tester Xuvero to test your expressions in real-time. The tool highlights matches and shows capture groups.
Regex in Different Programming Languages
JavaScript
const pattern = /^\d{3}-\d{2}-\d{2}$/; pattern.test("123-45-67"); // truePython
import re re.match(r'^\d{3}-\d{2}-\d{2}$', "123-45-67") # Match objectPHP
preg_match('/^\d{3}-\d{2}-\d{2}$/', "123-45-67"); // 1Common Mistakes
- Greediness β
.*will capture as much as possible. Use.*?for minimal match - Unescaped Special Characters β a dot
.without\matches any character - Missing Anchors β without
^and$, the expression will find partial matches