Regular expressions (regex) are one of the most powerful tools in a developer toolkit. Once you understand them, you will use them constantly for validation, parsing, and text manipulation.
Basic Syntax
// Test if string matches pattern
/pattern/.test("string") // โ true/false
// Find matches
"hello world".match(/\w+/g) // โ ["hello", "world"]
// Replace
"hello world".replace(/world/, "developer") // โ "hello developer"
Character Classes
. โ Any character except newline
\d โ Digit (0-9)
\D โ Non-digit
\w โ Word character (a-z, A-Z, 0-9, _)
\W โ Non-word character
\s โ Whitespace (space, tab, newline)
\S โ Non-whitespace
[abc] โ Character set (a, b, or c)
[^abc] โ Negated set (not a, b, or c)
[a-z] โ Range (any lowercase letter)
[A-Z0-9] โ Multiple ranges
Quantifiers
* โ Zero or more
+ โ One or more
? โ Zero or one (optional)
{3} โ Exactly 3
{3,} โ 3 or more
{3,6} โ Between 3 and 6
*? โ Lazy (as few as possible)
+? โ Lazy
Real-World Examples
// Email validation
const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
emailRegex.test("user@example.com") // โ true
// Phone number (international)
const phoneRegex = /^\+?[\d\s\-\(\)]{10,15}$/;
// URL validation
const urlRegex = /^https?:\/\/(www\.)?[-a-zA-Z0-9@:%._+~#=]{2,256}\.[a-z]{2,6}\b/;
// Password (min 8 chars, letter + number)
const pwdRegex = /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d@$!%*#?&]{8,}$/;
// Extract all hashtags from text
const tags = "#flutter #android #kotlin".match(/#\w+/g);
// โ ["#flutter", "#android", "#kotlin"]
Kotlin Regex
// Kotlin regex
val emailRegex = Regex("""^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$""")
emailRegex.matches("user@example.com") // true
// Find all matches
val text = "Call 123-456-7890 or 987-654-3210"
val phoneRegex = Regex("""\d{3}-\d{3}-\d{4}""")
val phones = phoneRegex.findAll(text).map { it.value }.toList()
// โ ["123-456-7890", "987-654-3210"]
// Replace with transformation
val result = "hello world".replace(Regex("""\b\w""")) { it.value.uppercase() }
// โ "Hello World"
๐ Test Regex Instantly
Test and debug your regular expressions with real-time highlighting, match groups, and a pattern library in our free Regex Tester.
Open Regex Tester โ