Common Regex Examples
A practical collection of common regular expression examples for validating, searching, extracting, and replacing everyday text patterns.
Regular expressions are useful whenever an application needs to find, validate, extract, or replace text that follows a recognizable pattern. Instead of checking every character manually, a regex can describe the structure that valid or interesting text should have.
This guide collects practical regex examples that appear frequently in web development and everyday text processing. The examples cover email addresses, URLs, phone numbers, dates, times, numbers, usernames, passwords, slugs, hexadecimal colors, IP addresses, whitespace, repeated characters, and other common patterns.
These expressions are intended as useful starting points rather than universal definitions. Real-world data is often more complicated than a compact regex can express, so validation rules should match the actual requirements of your application.
Regex Syntax Used in the Examples
| Syntax | Meaning |
|---|---|
| ^ | Start of the input or line |
| $ | End of the input or line |
| . | Any character except line terminators by default |
| \d | A digit |
| \w | A word character |
| \s | Whitespace |
| + | One or more occurrences |
| * | Zero or more occurrences |
| ? | Zero or one occurrence |
| {n} | Exactly n occurrences |
| {n,m} | Between n and m occurrences |
| [abc] | One character from the listed set |
| [^abc] | One character not in the listed set |
| (...) | Capturing group |
| (?:...) | Non-capturing group |
| | | Alternation |
1. Email Address
Email validation is one of the most common reasons developers reach for regex. A practical application often needs to verify that an input resembles an email address before sending it to a server.
/^[^\s@]+@[^\s@]+\.[^\s@]+$/This pattern checks for a non-whitespace sequence before an @ symbol, a domain-like sequence after it, and a dot-separated suffix.
const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
emailPattern.test("[email protected]");
// true
emailPattern.test("invalid-email");
// false2. URL
URLs can contain protocols, credentials, ports, paths, query strings, fragments, internationalized domains, and many other components. A simple regex can check for a common HTTP or HTTPS URL shape.
^https?:\/\/[^\s]+$const urlPattern = /^https?:\/\/[^\s]+$/;
urlPattern.test("https://example.com");
// true
urlPattern.test("ftp://example.com");
// falseFor parsing or fully validating URLs in JavaScript, the built-in URL class is generally more appropriate than attempting to reproduce the complete URL grammar with regex.
3. HTTP or HTTPS URL
If an application specifically requires a web URL, the protocol can be restricted to HTTP or HTTPS.
/^https?:\/\/(?:www\.)?[^\s]+$/The optional non-capturing group allows URLs with or without the www subdomain.
4. Phone Number
Phone number formats vary significantly between countries. Instead of trying to create one regex for every possible phone number, it is often better to define the format your application actually accepts.
/^\+?[0-9\s()-]{7,20}$/This example permits an optional plus sign and allows digits, spaces, parentheses, and hyphens. It also limits the total length.
const phonePattern = /^\+?[0-9\s()-]{7,20}$/;
phonePattern.test("+1 (555) 123-4567");
// true5. Digits Only
To check whether a string contains only ASCII digits, use a character class with anchors.
/^\d+$//^\d+$/.test("123456");
// true
/^\d+$/.test("123abc");
// falseThe + quantifier requires at least one digit. If an empty string should also be accepted, the quantifier would need to change.
6. Exactly N Digits
Use a fixed quantifier when a value must contain an exact number of digits.
/^\d{6}$/This can be useful for six-digit verification codes.
7. One to Ten Digits
/^\d{1,10}$/The {1,10} quantifier requires at least one digit and permits no more than ten.
8. Integer Numbers
A basic integer pattern can allow an optional minus sign followed by one or more digits.
/^-?\d+$/This accepts values such as 42 and -42, but not decimal numbers.
9. Positive Integer
/^\d+$/This pattern accepts zero as well. If the application requires a number greater than zero, regex alone is often not the clearest way to express the numeric rule. Parse the value and perform a numeric comparison after basic format validation.
10. Decimal Number
A simple decimal pattern can support an optional minus sign and a decimal fraction.
/^-?\d+(?:\.\d+)?$/This accepts 10, -10, 10.5, and -10.5.
11. Decimal with Optional Leading Digits
/^-?(?:\d+(?:\.\d+)?|\.\d+)$/This version also accepts values such as .5 and -.5. Whether those forms should be allowed depends on the application's input rules.
12. Percentage
A simple percentage pattern can allow an integer or decimal number followed by the percent sign.
/^\d+(?:\.\d+)?%$/This checks the format but does not enforce the mathematical range from 0% to 100%. A numeric range check should be performed separately when that restriction matters.
13. Hexadecimal Color
Hexadecimal colors commonly use either three or six hexadecimal digits after #.
/^#(?:[0-9A-Fa-f]{3}|[0-9A-Fa-f]{6})$/const colorPattern = /^#(?:[0-9A-Fa-f]{3}|[0-9A-Fa-f]{6})$/;
colorPattern.test("#fff");
// true
colorPattern.test("#12a4ff");
// true
colorPattern.test("#12345");
// false14. CSS Hex Color with Optional Alpha
If the application accepts eight-digit hexadecimal colors such as #RRGGBBAA, the pattern can be extended.
/^#(?:[0-9A-Fa-f]{3}|[0-9A-Fa-f]{4}|[0-9A-Fa-f]{6}|[0-9A-Fa-f]{8})$/For production CSS processing, browser parsing or a dedicated color parser may be preferable when the accepted syntax is broader than these forms.
15. Username
A common username rule is to allow letters, digits, underscores, and hyphens within a defined length.
/^[A-Za-z0-9_-]{3,20}$/This example accepts usernames between three and twenty characters and restricts the allowed character set.
16. Lowercase Username
/^[a-z0-9_-]{3,20}$/This version allows only lowercase ASCII letters, digits, underscores, and hyphens.
17. Username Starting with a Letter
/^[A-Za-z][A-Za-z0-9_-]{2,19}$/The first character must be a letter, followed by two to nineteen allowed characters.
18. Strong Password Format
Password requirements are a common use case for lookaheads. A typical example requires at least eight characters, one lowercase letter, one uppercase letter, and one digit.
^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).{8,}$The lookaheads check that required character types occur somewhere in the string, while .{8,} enforces the minimum length.
19. Password with a Special Character
^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[^A-Za-z0-9]).{8,}$The final lookahead requires at least one character outside the ASCII letters and digits.
20. Date in YYYY-MM-DD Format
A basic ISO-like date format can be checked with a simple structural regex.
/^\d{4}-\d{2}-\d{2}$/This validates the shape 2026-09-03, but it does not prove that the date actually exists. For example, 2026-99-99 matches the structure but is not a valid calendar date.
21. Date in DD/MM/YYYY Format
/^\d{2}\/\d{2}\/\d{4}$/This checks the structure of dates such as 03/09/2026. It does not determine whether the day and month form a real calendar date.
22. Time in HH:MM Format
A more constrained expression can validate a 24-hour time between 00:00 and 23:59.
/^(?:[01]\d|2[0-3]):[0-5]\d$/const timePattern = /^(?:[01]\d|2[0-3]):[0-5]\d$/;
console.log(timePattern.test("09:30"));
// true
console.log(timePattern.test("25:30"));
// false23. Date and Time
/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}$/This checks a simple YYYY-MM-DD HH:MM format. It should not be treated as a complete date-time validator because it does not validate calendar rules or time zones.
24. IPv4 Address
A simple IPv4 regex can check whether four groups of digits are separated by dots.
/^(?:\d{1,3}\.){3}\d{1,3}$/However, this accepts values such as 999.999.999.999 because the regex only checks the number of digits. A stricter IPv4 pattern can enforce the 0–255 range.
^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$25. IPv6
IPv6 addresses are significantly more complicated because they support compressed notation, hexadecimal groups, and multiple valid representations.
Instead of maintaining a very large IPv6 regex, application code should generally use a dedicated IP parser or networking library when complete validation is required.
26. Slug
A common URL slug convention allows lowercase letters, digits, and hyphens.
/^[a-z0-9]+(?:-[a-z0-9]+)*$/const slugPattern = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
slugPattern.test("hello-world");
// true
slugPattern.test("Hello World");
// falseThis pattern prevents leading, trailing, and consecutive hyphens.
27. Extract Words
A simple word-oriented expression can find sequences of word characters.
/\b\w+\b/gThe word boundary markers help isolate word-like sequences. Remember that \w is ASCII-oriented in common JavaScript usage, so it should not automatically be treated as a complete Unicode word definition.
28. Extract Numbers
/\d+/gconst text = "Order 123 contains 45 items";
const numbers = text.match(/\d+/g);
console.log(numbers);
// ["123", "45"]29. Extract Decimal Numbers
/\d+(?:\.\d+)?/gThis finds integer and decimal numbers such as 42, 3.14, and 100.5. More advanced numeric formats such as scientific notation require additional rules.
30. Find Repeated Words
Capturing groups and backreferences can detect an immediately repeated word.
\b(\w+)\s+\1\bconst pattern = /\b(\w+)\s+\1\b/i;
pattern.test("This is is a test");
// trueThe first group captures the word, while \1 requires the same captured text to appear again.
31. Remove Extra Spaces
Regex can find runs of whitespace that need to be normalized.
/\s+/gconst text = "hello world\nthis is text";
const normalized = text.replace(/\s+/g, " ").trim();
console.log(normalized);
// "hello world this is text"If line breaks need to be preserved, use a more specific whitespace rule instead of replacing every whitespace sequence.
32. Find Leading Whitespace
/^\s+/gmWith m, the pattern can find whitespace occurring at the beginning of each line.
33. Find Trailing Whitespace
/\s+$/gmThis is useful for detecting or removing spaces accidentally left at the end of lines.
34. Remove Empty Lines
/^\s*$/gmThe pattern matches lines containing only whitespace or nothing at all.
35. Find Lines Starting with a Prefix
Multiline mode makes it convenient to search for lines beginning with a particular string.
/^TODO:.*$/gmThis finds every line beginning with TODO:.
36. Find Hashtags
/#[A-Za-z0-9_]+/gconst text = "Learning #regex and #JavaScript";
const tags = text.match(/#[A-Za-z0-9_]+/g);
console.log(tags);
// ["#regex", "#JavaScript"]If hashtags need to support Unicode letters or application-specific characters, the character set should be adapted to those requirements.
37. Find Mentions
/@[A-Za-z0-9_]+/gThis pattern can extract simple @username-style mentions from text.
38. Find Markdown Links
A basic Markdown link pattern can capture the text and URL from simple links.
/\[([^\]]+)\]\(([^)]+)\)/gThe first capturing group contains the link text and the second contains the URL. This simplified pattern does not support every valid Markdown link form.
39. Find Quoted Text
A lazy quantifier can capture text between double quotes in simple cases.
/".*?"/gThis works for basic quoted strings, but escaped quotes and nested structures require a more careful pattern or a parser.
40. Find Text Between Parentheses
/\([^()]*\)/gThis handles parentheses without nested parentheses. Nested structures are difficult to represent with ordinary JavaScript regex and may be better handled by a parser.
41. Remove HTML Tags
/<[^>]*>/gThis pattern can be useful for simple text-cleaning tasks, but it should not be considered a complete HTML parser or a safe HTML sanitization strategy.
42. Find File Extensions
A simple expression can find an extension at the end of a filename.
/\.([A-Za-z0-9]+)$/const match = "photo.jpg".match(/\.([A-Za-z0-9]+)$/);
console.log(match?.[1]);
// "jpg"43. Match Specific File Extensions
Alternation can restrict the accepted extensions.
/\.(?:jpg|jpeg|png|webp)$/iThe i flag makes the extension check case-insensitive.
44. Find Duplicate Lines
Regex can help identify some repeated line patterns, but detecting duplicates across an entire document is usually easier with code that stores previously seen lines.
/^(.+)\n\1$/mThis demonstrates a backreference for a very specific adjacent-line situation. It is not a general duplicate-line detector.
45. Match a Simple JSON-Like Key
/"([^"\\]+)"\s*:/gThis can locate simple quoted object keys in JSON-like text. It should not replace a JSON parser when the input is actual JSON.
46. Find CSS Hex Colors in Text
/#[0-9A-Fa-f]{3,8}\b/gThis is useful for extracting color-like tokens from source text, although a real CSS parser is preferable when complete CSS syntax needs to be understood.
47. Match a Semantic Version
A basic semantic-version pattern can check versions such as 1.2.3.
/^\d+\.\d+\.\d+$/This only checks the core numeric version. Full Semantic Versioning also allows prerelease identifiers and build metadata.
48. Match a Basic Git Branch Name
/^(?:feature|fix|chore|docs)\/[a-z0-9]+(?:-[a-z0-9]+)*$/This example accepts branch names such as feature/add-login or fix/header-bug according to a deliberately simplified naming convention.
49. Find CamelCase Words
/\b[A-Z][a-zA-Z0-9]*\b/gThis can find words beginning with an uppercase letter and containing additional letters or digits. It is a heuristic rather than a formal definition of CamelCase.
50. Find kebab-case Words
/\b[a-z0-9]+(?:-[a-z0-9]+)+\b/gThis finds lowercase hyphen-separated tokens containing at least one hyphen.
51. Find snake_case Words
/\b[a-z0-9]+(?:_[a-z0-9]+)+\b/gThis finds lowercase underscore-separated identifiers containing at least one underscore.
52. Match a JavaScript Identifier
A simplified ASCII-oriented JavaScript identifier pattern can be written as follows.
/^[A-Za-z_$][A-Za-z0-9_$]*$/This does not represent every valid JavaScript identifier because JavaScript supports Unicode identifiers and has language-specific rules. Use a parser when exact language syntax matters.
53. Match Whitespace-Free Text
/^\S+$/The \S shorthand matches non-whitespace characters, so this pattern requires at least one character and no whitespace.
54. Match Non-Empty Text
/\S/This checks whether a string contains at least one non-whitespace character. It is useful when a field should not consist entirely of spaces.
55. Remove Comments from Simple Text
/\/\/.*$/gmThis finds JavaScript-style single-line comments in simple source text. It is not a JavaScript parser and can produce incorrect results inside strings, regular expressions, URLs, or other contexts where // has a different meaning.
56. Find TODO Comments
/\/\/\s*TODO\b.*$/gmThis is useful for quickly locating TODO comments in source files.
57. Find Lines Containing a Word
/^.*\berror\b.*$/gimThe g flag finds all matching lines, m enables line-based anchors, and i makes the search case-insensitive.
58. Extract Text After a Prefix
Capturing groups can extract the portion of a line that follows a known prefix.
/^Name:\s*(.+)$/mconst text = "Name: Danil";
const match = text.match(/^Name:\s*(.+)$/m);
console.log(match?.[1]);
// "Danil"59. Extract Text Before a Delimiter
/^([^:]+):/The capturing group extracts everything before the first colon in a simple input.
60. Find URLs in Text
A lightweight URL extraction pattern can look for HTTP or HTTPS URLs surrounded by non-whitespace characters.
/https?:\/\/[^\s]+/gThis is convenient for simple text extraction, but punctuation attached to URLs and complex URL syntax may require additional processing.
61. Find Email Addresses in Text
/[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}/gThis pattern is intended for practical extraction rather than complete RFC-level email parsing.
62. Find Numbers with Optional Signs
/[+-]?\d+(?:\.\d+)?/gThis can extract simple positive and negative integer or decimal values from text.
63. Find Dates in Text
/\b\d{4}-\d{2}-\d{2}\b/gThis extracts strings that look like YYYY-MM-DD dates. It does not determine whether each date is a valid calendar date.
64. Find Time Values in Text
/\b(?:[01]\d|2[0-3]):[0-5]\d\b/gThis finds simple 24-hour HH:MM values inside larger text.
65. Find Version Numbers
/\b\d+\.\d+(?:\.\d+)?\b/gThis can find version-like sequences such as 2.4 and 1.2.3. It is intentionally simpler than a full version parser.
Choosing Between Validation and Extraction
One of the most important distinctions when writing regex is whether the goal is validation or extraction. Validation usually uses ^ and $ to ensure the entire input follows a required format. Extraction often uses g to find matching portions inside a larger text.
| Task | Typical approach |
|---|---|
| Validate an email field | Anchor the pattern with ^ and $ |
| Find emails in a document | Use a matching pattern with g |
| Validate a slug | Anchor the entire slug |
| Extract hashtags | Use #... with g |
| Validate a date format | Anchor the entire input |
| Extract dates | Use a date pattern with g |
Why Anchors Matter
A regex without anchors can match a valid-looking substring inside invalid input. For example, \d+ finds digits anywhere in a string. If a field must contain only digits, ^\d+$ is more appropriate.
/\d+/.test("abc123xyz");
// true
/^\d+$/.test("abc123xyz");
// falseRegex Validation Does Not Always Mean Full Validation
A regex can verify that input follows a particular textual structure without proving that the underlying value is semantically valid. This distinction is especially important for dates, IP addresses, URLs, email addresses, numbers, and programming-language syntax.
| Input | Regex can check | Additional validation may need |
|---|---|---|
| Date | YYYY-MM-DD structure | Real calendar date |
| IPv4 | Four numeric components | Each component 0–255 |
| Common address shape | Deliverability and complete email syntax | |
| URL | Common URL structure | Complete URL parsing |
| Number | Textual numeric format | Numeric range and business rules |
| Password | Required character classes | Length, uniqueness, breached-password checks |
When Regex Is the Wrong Tool
Regex is powerful, but it is not a universal parser. Once the structure becomes nested, recursive, context-sensitive, or governed by a formal grammar, a dedicated parser is usually easier to understand and maintain.
- Use the URL class for parsing URLs in JavaScript.
- Use JSON.parse() for JSON.
- Use an HTML parser for HTML.
- Use a date library or date API for calendar calculations.
- Use numeric conversion and comparisons for numeric ranges.
- Use language parsers for source-code syntax.
- Use dedicated email verification when actual deliverability matters.
Making Common Regexes Easier to Maintain
Short regexes are often easier to maintain than large expressions containing many nested alternatives and lookarounds. When a pattern becomes difficult to explain, consider splitting the validation into several checks.
const hasLowercase = /[a-z]/.test(password);
const hasUppercase = /[A-Z]/.test(password);
const hasNumber = /\d/.test(password);
const isLongEnough = password.length >= 8;
const valid =
hasLowercase &&
hasUppercase &&
hasNumber &&
isLongEnough;This can be easier to read and debug than putting every requirement into one large lookahead expression.
Testing Common Regex Patterns
A regex should be tested against both valid and invalid examples. Testing only successful cases can hide problems such as partial matches, missing anchors, unexpected whitespace, or unsupported characters.
- Test the smallest valid input.
- Test the largest expected input.
- Test an empty string when relevant.
- Test unexpected whitespace.
- Test uppercase and lowercase variants.
- Test punctuation and special characters.
- Test Unicode input when international text is expected.
- Test malformed values that should be rejected.
- Test boundary values such as minimum and maximum lengths.
Frequently Asked Questions
What are the most common regex patterns?
Common patterns include email-like addresses, URLs, phone numbers, digits, integers, decimal numbers, dates, times, usernames, passwords, slugs, hexadecimal colors, IP addresses, hashtags, mentions, and whitespace.
How do I validate an email with regex?
For a practical web form, a simple pattern such as /^[^\s@]+@[^\s@]+\.[^\s@]+$/ can check the common structure of an email address. Complete email syntax and deliverability require more than a simple regex.
How do I match only numbers?
For ASCII digits only, /^\d+$/ requires the entire input to contain one or more digits. If the value can be decimal, signed, or formatted differently, the pattern should be adapted to those requirements.
How do I validate a date with regex?
A pattern such as /^\d{4}-\d{2}-\d{2}$/ checks the YYYY-MM-DD structure. It does not prove that the date exists, so calendar validation should be performed separately.
How do I create a regex for a slug?
A common lowercase slug pattern is /^[a-z0-9]+(?:-[a-z0-9]+)*$/. It permits lowercase letters and digits separated by single hyphens without leading, trailing, or consecutive hyphens.
Can regex validate a URL?
Regex can check a simplified URL format, but URLs have many rules and edge cases. In JavaScript, the built-in URL class is generally preferable for parsing and validating URLs according to the application's needs.
Can regex validate a password?
Regex can check textual password requirements such as minimum length and required character types. It cannot determine whether a password is genuinely secure, unique, or present in a leaked-password database.
Should I use one huge regex for validation?
Usually not. Large expressions can become difficult to understand and maintain. Splitting independent requirements into several readable checks is often easier to test and modify.
Conclusion
Common regex patterns can solve many everyday text-processing tasks. Simple expressions are often enough for checking digits, usernames, slugs, colors, dates, times, and basic input formats, while groups, lookaheads, backreferences, anchors, and flags make more advanced patterns possible.
The most important step is to define exactly what the application needs before writing the regex. A pattern designed for extracting emails from text does not need the same constraints as one validating an email form. Likewise, checking the structure of a date is different from determining whether the date is actually valid.
Use these examples as starting points, test them against realistic input, and prefer dedicated parsers when the underlying format becomes too complex for a maintainable regular expression.