Website Address Validation Regex – CodePal
# Regex for validating website addresses (URLs)
To validate website addresses (URLs), we can use a regular expression. Here is an example of a regex pattern that can match most common website addresses:
### A possible regex
“`
^(http(s)?://)?(www\.)?[a-zA-Z0-9-]+(\.[a-zA-Z]{2,})+(/[a-zA-Z0-9-]*)*(\?[a-zA-Z0-9-]+=[a-zA-Z0-9-%]*)?$
“`
### Regex Breakdown
“`
^ # Matches the start of the string
(http(s)?://)? # Matches an optional “http://” or “https://” prefix
(www\.)? # Matches an optional “www.” prefix
[a-zA-Z0-9-]+ # Matches one or more alphanumeric characters or hyphens (domain name)
(\.[a-zA-Z]{2,})+ # Matches one or more domain extensions (e.g., .com, .org)
(/[a-zA-Z0-9-]*)* # Matches optional path segments (e.g., /about, /products)
(\?[a-zA-Z0-9-]+=[a-zA-Z0-9-%]*)? # Matches an optional query string (e.g., ?param=value)
$ # Matches the end of the string
“`
### Examples
– `https://www.example.com`
– `http://subdomain.example.org/about`
– `www.example.com/products`
– `https://example.com/?param=value`
### Final notes
This regular expression can match most common website addresses, including those with or without “http://” or “https://” prefixes, with or without “www.” prefixes, and with optional path segments and query strings. However, it may not cover all possible variations or handle complex URLs with special characters. It is always recommended to test the regex pattern with various sample URLs to ensure it meets your specific requirements.
Read more here: Source link
