Regex (short for Regular Expression) is a sequence of characters that defines a search pattern. It is commonly used for searching, replacing, and validating text.
Regular characters match themselves:
hello
matches "hello" in a text.
.
→ Matches any character except a newline.^
→ Matches start of a string.$
→ Matches end of a string.*
→ Matches 0 or more occurrences.+
→ Matches 1 or more occurrences.?
→ Matches 0 or 1 occurrences.{n}
→ Matches exactly n occurrences.[abc]
→ Matches a, b, or c.[^abc]
→ Matches any character except a, b, or c.[0-9]
→ Matches any digit (0-9).\d
→ Matches any digit (0-9).\D
→ Matches non-digit characters.\w
→ Matches word characters (a-z, A-Z, 0-9, _).\s
→ Matches whitespace (space, tab, newline).(abc)
→ Groups abc together.(?:abc)
→ Non-capturing group.cat|dog
→ Matches "cat" OR "dog".
(?=abc)
→ Positive lookahead.(?!abc)
→ Negative lookahead.[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}
\d{3}-\d{3}-\d{4}
\d{2}[/-]\d{2}[/-]\d{4}
You can test regex patterns using:
import re
), JavaScript (RegExp
), Java (Pattern
).