HomeRegex LibrarySubdomain Extraction Regex
100% Client-Side β€’ 0 B Data Leaves Browser
web

Subdomain Extraction Regex

Captures and isolates the third-level subdomain prefix from a full hostname or URL.

Regular Expression Pattern:
/^(?:https?:\/\/)?([a-zA-Z0-9-]+)\.[a-zA-Z0-9-]+\.[a-zA-Z]{2,}/i
Valid Match Example:
https://staging.example.com
Invalid / Non-Match Example:
example.com

Regex Syntax Breakdown & Explanation

  • β€’(?:https?:\/\/)? : Disregards optional protocol schema
  • β€’([a-zA-Z0-9-]+) : First capturing group isolates the leading subdomain label
  • β€’\.[a-zA-Z0-9-]+\.[a-zA-Z]{2,} : Confirms presence of root domain and TLD

Implementation in Popular Languages

JavaScript / TypeScript
const regex = /^(?:https?:\/\/)?([a-zA-Z0-9-]+)\.[a-zA-Z0-9-]+\.[a-zA-Z]{2,}/i;
const isValid = regex.test("https://staging.example.com");
console.log(isValid); // true
Python (re)
import re

pattern = r"^(?:https?:\/\/)?([a-zA-Z0-9-]+)\.[a-zA-Z0-9-]+\.[a-zA-Z]{2,}"
match = re.match(pattern, "https://staging.example.com")
print(bool(match)) # True
Go (regexp)
package main
import (
  "fmt"
  "regexp"
)

func main() {
  re := regexp.MustCompile(`^(?:https?:\/\/)?([a-zA-Z0-9-]+)\.[a-zA-Z0-9-]+\.[a-zA-Z]{2,}`)
  fmt.Println(re.MatchString("https://staging.example.com"))
}
Frequently Asked Questions

Frequently Asked Questions

Everything you need to know regarding specifications, syntax, and security best practices.

The regular expression pattern is /^(?:https?:\/\/)?([a-zA-Z0-9-]+)\.[a-zA-Z0-9-]+\.[a-zA-Z]{2,}/i. Captures and isolates the third-level subdomain prefix from a full hostname or URL.