TechEarl

How to Match Numbers with Regex

Match integers, decimals, signed, scientific, thousands-separated, currency, and percent numbers with regex, plus the structured numbers people validate most: US phone numbers, credit card numbers with the Luhn check, and hex color codes. JavaScript / Python / PHP examples, engine notes, common mistakes, test tables.

Ishan KarunaratnePublished ⏱️ 15 min readUpdated
Share thisCopied
Regex to match integers, decimals, signed, scientific and currency numbers, plus US phone numbers, credit cards with Luhn, and hex colors. JS, Python, PHP.

The shortest regex for a positive integer: ^\d+$. For a signed integer (positive, negative, or zero): ^-?\d+$. For a decimal that may or may not have a fractional part: ^-?\d+(\.\d+)?$. The patterns get more specific from there: scientific notation, thousands-separated, percent-suffixed, currency-prefixed. Below I walk all of them with runnable code in JavaScript, Python, and PHP, engine notes, the bugs I see most often, and the case where regex stops being the right tool.

The fact you can have a different regex for "number" depending on context (form input vs CSV column vs log line) is why this question keeps coming up. The right pattern is the one that matches the exact subset your input might contain. The same toolkit covers three structured numbers people validate constantly, each in its own section below: US phone numbers, credit card numbers with the Luhn check, and hex color codes.

Quick reference

code
Positive integer:                ^\d+$
Signed integer:                  ^-?\d+$
Signed (explicit +/- allowed):   ^[+-]?\d+$
Non-zero positive integer:       ^[1-9]\d*$
Positive decimal:                ^\d+(\.\d+)?$
Signed decimal:                  ^-?\d+(\.\d+)?$
Scientific:                      ^-?\d+(\.\d+)?([eE][-+]?\d+)?$
US thousands-separated:          ^-?\d{1,3}(,\d{3})*(\.\d+)?$
Currency (USD):                  ^(?:-?\$|\$?-?)\d+(,\d{3})*(\.\d{2})?$
Percent:                         ^-?\d+(\.\d+)?%$

The basic patterns

code
Positive integer:        ^\d+$
Signed integer:          ^-?\d+$
Signed-or-unsigned:      ^[+-]?\d+$
Integer with leading 0:  ^0\d+$
Non-zero positive:       ^[1-9]\d*$
  • \d matches a digit. \d+ requires at least one. ^ and $ anchor to the full string.
  • -? makes the minus sign optional.
  • [+-]? allows either explicit sign.
  • [1-9]\d* enforces no leading zero (the first digit cannot be 0).

The non-zero-leading version is useful when you don't want 0123 interpreted as 123 (which would be the case if the application parsed it as an integer).

Decimal numbers

code
Positive decimal:                     ^\d+(\.\d+)?$
Decimal with optional integer part:   ^(\d+\.\d+|\.\d+|\d+\.?)$
Signed decimal:                       ^-?\d+(\.\d+)?$
Decimal with fixed precision (2dp):   ^-?\d+\.\d{2}$

The bare positive form accepts integers too because the fractional part is optional. The "optional integer part" form additionally accepts .5 (no leading digit) and 5. (trailing dot). Most form fields use the first form.

The fixed-precision form is useful for currency: ^-?\d+\.\d{2}$ requires exactly two decimal places.

Scientific notation

code
^-?\d+(\.\d+)?([eE][-+]?\d+)?$

Adds an optional exponent part: e or E, optional sign, one or more digits. Matches 1.5e10, -2.7E-9, and plain 42 (the exponent is optional).

Thousands-separated numbers (1,234,567.89)

The pattern depends on the locale's separator. For US-style commas:

code
^-?\d{1,3}(,\d{3})*(\.\d+)?$
  • \d{1,3} for the first group (1-3 digits before any comma).
  • (,\d{3})* for zero or more comma-prefixed three-digit groups.
  • (\.\d+)? for the optional decimal part.

This matches 1,234, 1,234,567.89, and rejects 1,2345 (wrong grouping) and ,123 (leading comma). For European locales that use . as thousands and , as decimal, swap them.

Currency and percent

code
USD currency:    ^(?:-?\$|\$?-?)\d+(,\d{3})*(\.\d{2})?$
Percent:         ^-?\d+(\.\d+)?%$

The currency pattern allows the $ either before the sign or after, since both $-50 and -$50 are seen in the wild.

Examples in JavaScript, Python, and PHP

JavaScript:

javascript
const patterns = {
  integer:    /^-?\d+$/,
  decimal:    /^-?\d+(\.\d+)?$/,
  scientific: /^-?\d+(\.\d+)?([eE][-+]?\d+)?$/,
  currency:   /^(?:-?\$|\$?-?)\d+(,\d{3})*(\.\d{2})?$/,
};

function teClassify(input) {
  for (const [name, pattern] of Object.entries(patterns)) {
    if (pattern.test(input)) return name;
  }
  return null;
}

teClassify("42");          // 'integer'
teClassify("-3.14");       // 'decimal'
teClassify("1.5e10");      // 'scientific'
teClassify("$1,234.56");   // 'currency'

Python:

python
import re

INTEGER    = re.compile(r"^-?\d+$")
DECIMAL    = re.compile(r"^-?\d+(\.\d+)?$")
SCIENTIFIC = re.compile(r"^-?\d+(\.\d+)?([eE][-+]?\d+)?$")

def te_is_number(value: str) -> bool:
    return bool(SCIENTIFIC.match(value))

te_is_number("42")       # True
te_is_number("-3.14")    # True
te_is_number("1.5e10")   # True
te_is_number("3.14.15")  # False

PHP:

php
function te_is_number(string $value): bool {
    return (bool) preg_match('/^-?\d+(\.\d+)?([eE][-+]?\d+)?$/', $value);
}

// Or use the built-in:
is_numeric("42");       // true
is_numeric("-3.14");    // true
is_numeric("0x1A");     // true (also accepts hex, regex above does not)
is_numeric("1e10");     // true (scientific)

In PHP, is_numeric is broader than the regex (it accepts hex and binary in some versions). Use the regex when you want to lock down exactly which numeric forms are acceptable.

Engine compatibility

These patterns use only universal features. They run unmodified everywhere. The per-engine notes are about parse helpers when the regex passes and you want the actual numeric value.

EnginePractical patternNative parse helper
JavaScriptWorksNumber(s) and parseFloat(s). Number.isFinite(Number(s)) filters non-numbers.
Python (re)Worksint(s), float(s), decimal.Decimal(s). Raise ValueError on bad input.
PHP (PCRE)Worksis_numeric($v) is broader than the regex (accepts hex/octal in older versions).
JavaWorksInteger.parseInt, Double.parseDouble, BigDecimal.new.
.NETWorksint.TryParse, decimal.TryParse(s, NumberStyles.Currency, ...).
Go (RE2)Worksstrconv.Atoi, strconv.ParseFloat. No lookaround so the strict patterns below stay simple.
Rust (regex crate)Workss.parse::<i64>(), s.parse::<f64>().
RubyWorksInteger(s) and Float(s) raise on invalid. s.to_i silently accepts garbage.
POSIX ERE (grep -E)Works (replace \d with [0-9])None; combine with shell arithmetic

I usually run the regex first to confirm the input is shaped right, then Number(s) (JavaScript) or Decimal(s) (Python) for the actual numeric conversion. Skipping the regex and relying on Number(s) alone is also fine if you don't mind NaN for invalid input.

Common mistakes

The bugs I see most often.

Forgetting the second anchor. ^\d+ matches 42abc because nothing pins the end. For validation, anchor both ends.

Treating \d as ASCII-only everywhere. \d is ASCII 0-9 in JavaScript by default, but whether it also matches other scripts' digits in Python, PCRE, .NET or Java depends on the engine and its Unicode options (PCRE's (*UCP) mode is one example). When you need strictly ASCII digits, write [0-9]. If your input might include 0 (full-width digit) or Arabic-Indic numerals, decide whether to accept them and choose the engine flag accordingly.

Not handling the explicit + sign. ^-?\d+$ rejects +42 because + is not in the pattern. Use ^[+-]?\d+$ if you want to accept either explicit sign.

Accepting leading zeros silently. Some applications interpret a leading zero as octal. ^[1-9]\d*$ or ^(0|[1-9]\d*)$ are the safer forms for inputs the application will later parse as an integer.

Locale confusion. US uses , for thousands and . for decimal. Most of Europe uses . for thousands and , for decimal. The pattern needs to match the locale of the input, not the locale of the developer.

Trusting the regex to validate the range. ^\d+$ matches 99999999999999999999999999 (way past 64-bit). If your downstream code is int(s), that throws; if it's Number(s), you get Infinity or a loss-of-precision float. Add a length cap or parse and check.

Test cases

InputIntegerDecimalScientific
42MatchMatchMatch
-42MatchMatchMatch
+42No matchNo matchNo match
3.14No matchMatchMatch
-3.14No matchMatchMatch
.5No matchNo matchNo match
5.No matchNo matchNo match
1.5e10No matchNo matchMatch
1,234No matchNo matchNo match
0123MatchMatchMatch
1eNo matchNo matchNo match

Validate a US phone number with regex

A phone number is a number with structure, and the practical pattern accepts an optional +1 country code, optional parentheses around the area code, and a dash, dot or space between groups, so (415) 555-0132, +1 415-555-0132, 415.555.0132 and 4155550132 all match:

code
Exactly 10 digits, no formatting:  ^\d{10}$
Optional +1, digits only:          ^(?:\+?1)?\d{10}$
Practical:                         ^(?:\+?1[-.\s]?)?\(?\d{3}\)?[-.\s]?\d{3}[-.\s]?\d{4}$
Stricter (NANP):                   ^(?:\+?1[-.\s]?)?\(?[2-9]\d{2}\)?[-.\s]?[2-9]\d{2}[-.\s]?\d{4}$

Left to right in the practical pattern: (?:\+?1[-.\s]?)? is the optional country code in a non-capturing group, \(? and \)? are the escaped optional parentheses, \d{3} is the area code, [-.\s]? an optional separator, \d{3} the exchange (central office) code, and \d{4} the subscriber number. The stricter version applies two North American Numbering Plan rules: neither the area code nor the exchange code may start with 0 or 1. That one-character change per group rejects (011) 234-5678 and 123-456-7890, and it is the version I use on a signup form.

javascript
const phonePattern = /^(?:\+?1[-.\s]?)?\(?\d{3}\)?[-.\s]?\d{3}[-.\s]?\d{4}$/;

phonePattern.test("(415) 555-0132");   // true
phonePattern.test("+1 415-555-0132");  // true
phonePattern.test("555-0132");         // false
python
import re

phone_pattern = re.compile(r"^(?:\+?1[-.\s]?)?\(?\d{3}\)?[-.\s]?\d{3}[-.\s]?\d{4}$")

bool(phone_pattern.match("(415) 555-0132"))   # True
bool(phone_pattern.match("555-0132"))         # False
php
$pattern = '/^(?:\+?1[-.\s]?)?\(?\d{3}\)?[-.\s]?\d{3}[-.\s]?\d{4}$/';

preg_match($pattern, '(415) 555-0132');  // 1
preg_match($pattern, '555-0132');        // 0

In an HTML form it drops straight into the pattern attribute for instant feedback with no JavaScript:

html
<input
  type="tel"
  pattern="^(?:\+?1[-.\s]?)?\(?\d{3}\)?[-.\s]?\d{3}[-.\s]?\d{4}$"
  title="Enter a US phone number, like +1 415-555-0132 or (415) 555-0132"
/>

What it still lets through. The pattern checks shape, not validity. (415 555-0132 matches because the two parentheses are independently optional. Numbers in the 555-0100 to 555-0199 block reserved for fiction, service codes like 211 and 911, and unassigned area codes all pass; those need a lookup table. The cleaner design is to strip every non-digit first (value.replace(/\D/g, "") in JavaScript, re.sub(r"\D", "", value) in Python), validate the result against ^1?\d{10}$, and store that canonical form. Leave the multiline flag off: with /m or re.MULTILINE, not a phone\n4155550132 matches on its second line. A vanity number like 1-800-FLOWERS should be converted to digits before validating, not handled by widening the regex. For real reachability, send a verification text; for other countries, use a maintained library such as Google's libphonenumber rather than one giant regex.

InputPractical patternNotes
4155550132MatchBare 10 digits
(415) 555-0132MatchParentheses and a space
+14155550132MatchCountry code, no separators
555-0132No matchOnly seven digits, no area code
415-555-01324No matchToo many digits
1-800-FLOWERSNo matchLetters are not digits

Validate a credit card number with regex and Luhn

Card validation is two steps: a regex confirms the number has the right length and issuer prefix, and a Luhn checksum confirms the digits. Regex cannot do the second half because it has no arithmetic. Strip spaces and hyphens first; these patterns are anchored and digits-only:

code
Visa:        ^4[0-9]{12}(?:[0-9]{3})?$
MasterCard:  ^(?:5[1-5][0-9]{14}|2(?:2(?:2[1-9]|[3-9][0-9])|[3-6][0-9]{2}|7(?:[01][0-9]|20))[0-9]{12})$
Amex:        ^3[47][0-9]{13}$
Discover:    ^6(?:011|5[0-9]{2})[0-9]{12}$
Diners Club: ^3(?:0[0-5]|[68][0-9])[0-9]{11}$
JCB:         ^(?:2131|1800|35\d{3})\d{11}$

Any major card:
^(?:4[0-9]{12}(?:[0-9]{3})?|5[1-5][0-9]{14}|3[47][0-9]{13}|6(?:011|5[0-9]{2})[0-9]{12}|3(?:0[0-5]|[68][0-9])[0-9]{11}|(?:2131|1800|35\d{3})\d{11})$

Visa issues 13- and 16-digit numbers, which is why its last three digits are optional. The MasterCard pattern includes the 2-series range (2221 to 2720) added in 2016; a legacy ^5[1-5] check rejects those valid cards. Luhn: from the rightmost digit moving left, double every second digit, subtract 9 from any result of 10 or more, sum everything, and the total must be divisible by 10. Every major brand uses it; UnionPay is the notable exception, where most cards do not.

javascript
const cardPatterns = {
  visa:       /^4[0-9]{12}(?:[0-9]{3})?$/,
  mastercard: /^(?:5[1-5][0-9]{14}|2(?:2(?:2[1-9]|[3-9][0-9])|[3-6][0-9]{2}|7(?:[01][0-9]|20))[0-9]{12})$/,
  amex:       /^3[47][0-9]{13}$/,
  discover:   /^6(?:011|5[0-9]{2})[0-9]{12}$/,
};

function tePassesLuhn(digits) {
  let sum = 0;
  let alt = false;
  for (let i = digits.length - 1; i >= 0; i--) {
    let n = parseInt(digits[i], 10);
    if (alt) {
      n *= 2;
      if (n > 9) n -= 9;
    }
    sum += n;
    alt = !alt;
  }
  return sum % 10 === 0;
}

function teValidateCard(raw) {
  const digits = raw.replace(/\D/g, "");
  for (const [brand, pattern] of Object.entries(cardPatterns)) {
    if (pattern.test(digits) && tePassesLuhn(digits)) return brand;
  }
  return null;
}

teValidateCard("4532 0151 1283 0366");  // 'visa'
teValidateCard("4532 0151 1283 0367");  // null (Luhn fails)
python
import re

CARD_PATTERNS = {
    "visa":       re.compile(r"^4[0-9]{12}(?:[0-9]{3})?$"),
    "mastercard": re.compile(r"^(?:5[1-5][0-9]{14}|2(?:2(?:2[1-9]|[3-9][0-9])|[3-6][0-9]{2}|7(?:[01][0-9]|20))[0-9]{12})$"),
    "amex":       re.compile(r"^3[47][0-9]{13}$"),
    "discover":   re.compile(r"^6(?:011|5[0-9]{2})[0-9]{12}$"),
}

def te_passes_luhn(digits: str) -> bool:
    total = 0
    for i, ch in enumerate(reversed(digits)):
        n = int(ch)
        if i % 2 == 1:
            n *= 2
            if n > 9:
                n -= 9
        total += n
    return total % 10 == 0

def te_validate_card(raw: str):
    digits = re.sub(r"\D", "", raw)
    for brand, pat in CARD_PATTERNS.items():
        if pat.match(digits) and te_passes_luhn(digits):
            return brand
    return None
php
function te_passes_luhn(string $digits): bool {
    $sum = 0;
    $alt = false;
    for ($i = strlen($digits) - 1; $i >= 0; $i--) {
        $n = (int) $digits[$i];
        if ($alt) {
            $n *= 2;
            if ($n > 9) $n -= 9;
        }
        $sum += $n;
        $alt = !$alt;
    }
    return $sum % 10 === 0;
}

function te_validate_card(string $raw): ?string {
    $digits = preg_replace('/\D/', '', $raw);
    $patterns = [
        'visa'       => '/^4[0-9]{12}(?:[0-9]{3})?$/',
        'mastercard' => '/^(?:5[1-5][0-9]{14}|2(?:2(?:2[1-9]|[3-9][0-9])|[3-6][0-9]{2}|7(?:[01][0-9]|20))[0-9]{12})$/',
        'amex'       => '/^3[47][0-9]{13}$/',
        'discover'   => '/^6(?:011|5[0-9]{2})[0-9]{12}$/',
    ];
    foreach ($patterns as $brand => $pattern) {
        if (preg_match($pattern, $digits) && te_passes_luhn($digits)) {
            return $brand;
        }
    }
    return null;
}

The mistakes I see in review: putting spaces into the character class instead of normalising (^4[0-9 ]{12,16}$ happily accepts a 4 followed by spaces), checking only the prefix and not the length, doubling digits from the left instead of the right, and skipping the subtract-9 step. And never store the number after validating it: outside a PCI-DSS tokenisation system that is a compliance problem. Send the card straight to a processor (Stripe Elements, Braintree Hosted Fields) and keep the token. This check is client-side typo detection only.

InputBrandLuhnResult
4532 0151 1283 0366VisaPassvisa
4532 0151 1283 0367VisaFailnull (Luhn fails)
5454 5454 5454 5454MCPassmastercard
3782 822463 10005AmexPassamex
6011 1111 1111 1117DiscoverPassdiscover
1234 5678 9012 3456NoneNonenull (no brand)

Match a hex color code with regex

A hex color is hex digits rather than decimal ones. The practical pattern accepts the 3-character shorthand and the 6-character form, with or without the hash, in either case:

code
3 or 6 digits, optional hash:  ^#?([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$
With alpha (8 or 4 digits):    ^#?([A-Fa-f0-9]{8}|[A-Fa-f0-9]{6}|[A-Fa-f0-9]{4}|[A-Fa-f0-9]{3})$
Lowercase only:                ^#?([a-f0-9]{6}|[a-f0-9]{3})$
Hash already stripped:         ^([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$

List the longer alternative first. With anchors either order works, but in an unanchored pattern the engine would take the first three digits of a six-digit color as shorthand. The alpha forms #RRGGBBAA and #RGBA come from CSS Color Module Level 4, and shorthand expands by doubling each digit (#f08c is #ff0088cc). Use the explicit [A-Fa-f0-9] class, never \w, which lets #GHIJKL through, and do not half-implement alpha (accepting 4 digits but not 8, or the reverse).

javascript
const hexColor = /^#?([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/;

function teNormalizeHex(input) {
  if (!hexColor.test(input)) return null;
  let hex = input.startsWith("#") ? input.slice(1) : input;
  if (hex.length === 3) {
    // Expand shorthand: fff -> ffffff
    hex = hex.split("").map(c => c + c).join("");
  }
  return "#" + hex.toLowerCase();
}

teNormalizeHex("#FFF");        // '#ffffff'
teNormalizeHex("aB1");         // '#aabb11'
teNormalizeHex("not-a-color"); // null
python
import re

HEX_COLOR = re.compile(r"^#?([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$")

def te_is_valid_hex(value: str) -> bool:
    return bool(HEX_COLOR.match(value))

te_is_valid_hex("#a1b2c3")  # True
te_is_valid_hex("abc")      # True (shorthand without hash)
te_is_valid_hex("#1234")    # False (4 digits, no alpha pattern)
php
function te_is_valid_hex(string $value): bool {
    return (bool) preg_match('/^#?([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/', $value);
}

te_is_valid_hex("#ff0080");   // true
te_is_valid_hex("#F08");      // true (shorthand, uppercase)

To pull colors out of a CSS file instead of validating one value, drop the anchors and use a boundary: \B#([A-Fa-f0-9]{8}|[A-Fa-f0-9]{6}|[A-Fa-f0-9]{4}|[A-Fa-f0-9]{3})\b. After validating, each channel is a two-character pair you parse base 16 (parseInt(c, 16), int(h, 16), hexdec()).

InputPractical patternWith alpha
#ff0080MatchMatch
ff0080MatchMatch
#FFFMatchMatch
#ff0080ccNo matchMatch
#1234No matchMatch
rgb(255,0,128)No matchNo match
#zzzNo matchNo match
#1234567No matchNo match (7 digits)

FAQ

^\d+$ matches a string consisting of one or more digits with nothing else. To reject leading zeros (so 0123 fails), use ^[1-9]\d*$ for non-zero and ^(0|[1-9]\d*)$ for "zero or positive".

Add an optional minus sign: ^-?\d+$ for signed integers, ^-?\d+(\.\d+)?$ for signed decimals. To accept either sign explicitly: ^[+-]?\d+$.

To require a sign (no unsigned numbers): ^[+-]\d+$.

^-?\d+(\.\d+)?$ matches a number with an optional fractional part. It accepts 42, 3.14, -3.14 but rejects .5 and 3. because both integer and fractional parts must have at least one digit.

For looser matching that accepts .5 and 3.: ^(\d+\.\d+|\.\d+|\d+\.?)$.

^-?\d+(\.\d+)?([eE][-+]?\d+)?$. The exponent part [eE][-+]?\d+ is optional and matches e10, E-5, e+99, etc.

For the IEEE 754 style that requires the exponent: ^-?\d+\.\d+[eE][-+]?\d+$.

US-style (comma thousands, dot decimal): ^-?\d{1,3}(,\d{3})*(\.\d+)?$. The first group is 1-3 digits, then any number of comma-and-three-digits groups, then an optional dot-decimal.

For European-style (dot thousands, comma decimal), swap the separators: ^-?\d{1,3}(\.\d{3})*(,\d+)?$.

Because \d+ accepts any sequence of digits, including ones that start with zero. To reject leading zeros, replace with [1-9]\d* for positive non-zero, or (0|[1-9]\d*) for zero or positive.

The reason this matters: some parsers treat leading-zero integers as octal, which silently changes the value.

The practical pattern ^(?:\+?1[-.\s]?)?\(?\d{3}\)?[-.\s]?\d{3}[-.\s]?\d{4}$ handles an optional +1, optional parentheses, and dash, dot, or space separators. To reject more bad input, use the stricter NANP version that requires the area code and exchange code to start with a digit from 2 to 9. For real reachability, send a verification text.

Because \d{3} matches any three digits, including 000. Replace the first \d of the area code and exchange code with [2-9] to enforce the NANP rule that neither starts with 0 or 1.

Do not write one regex for every country. Numbering plans vary too much in length and structure, and a pattern broad enough to accept all of them accepts almost anything. Use a maintained library such as Google's libphonenumber, and reserve regex for the single-country case.

No. Regex can confirm the length and issuer prefix, but it cannot verify the Luhn checksum because regex engines do not do arithmetic. Regex narrows the input to valid-looking, a Luhn function confirms the checksum, and the payment processor confirms the card is real and active.

Yes. Visa, MasterCard, Amex, Discover, JCB and Diners Club all use the same Luhn algorithm and differ only in prefix ranges and length. UnionPay is the notable exception: most UnionPay cards do not use Luhn.

Add 8-digit and 4-digit alternatives: ^#?([A-Fa-f0-9]{8}|[A-Fa-f0-9]{6}|[A-Fa-f0-9]{4}|[A-Fa-f0-9]{3})$. The 8-digit form is RRGGBBAA and the 4-digit form is RGBA shorthand, both from CSS Color Module Level 4.

Not arithmetically, no. Regex can't compare numeric ranges. The workaround is to cap the digit count: ^-?\d{1,10}$ matches numbers up to 10 digits, which is the upper bound of int32 (2,147,483,647).

For an exact check, parse the string and compare: parseInt(s, 10) <= 2147483647 in JavaScript.

See also

External reference: paste the patterns into regex101.com to test against your own inputs.

Sources

Authoritative references this article was fact-checked against.

TagsRegexNumber ValidationPhone NumbersCredit Card ValidationLuhn AlgorithmHex ColorRegular ExpressionsJavaScriptPythonPHP

Found this useful? Pass it on.

Copied

Ishan Karunaratne

Systems and Network Architect · Chief Technology Officer

Systems and network architect and Chief Technology Officer with more than two decades designing, building, and running production software, cloud and network architecture, Linux systems, and the bare metal underneath them, and lately working AI into the stack. A US Army veteran who served in Operation Iraqi Freedom. What I write here is drawn from the full arc of that work, across architecture, engineering, and operations, not any single job.

Keep reading

Related posts

Match a URL with regex. http/https schemes, schemeless and protocol-relative input, ports, paths, query strings, fragments. JavaScript / Python / PHP examples, engine notes, parser alternative, common mistakes, test table.

How to Match a URL with Regex

Match a URL with regex. Covers http/https schemes, schemeless and protocol-relative input, ports, paths, query strings, fragments, runnable JavaScript / Python / PHP, engine notes, and the URL parser alternative.

Match a domain name with regex. Basic labels, RFC 1035 length rules, subdomains, IDN punycode, trailing-dot form, JavaScript / Python / PHP examples, engine notes, and common mistakes.

How to Match a Domain Name with Regex

Match a domain name with regex. Basic labels, RFC 1035 length rules, subdomains, IDN punycode, trailing-dot form, JavaScript / Python / PHP examples, engine notes, and common mistakes.

Match an email address with regex. Practical pattern, a stricter RFC 5321 subset, JavaScript / Python / PHP examples, edge cases, engine compatibility, common mistakes, and a test table.

How to Match an Email Address with Regex

Match an email address with regex. The practical pattern, a stricter RFC 5321 subset, examples in JavaScript, Python, and PHP, edge cases, engine compatibility, common mistakes, and a validation test table.