How to validate a domain name using Regular Expression
Last Updated :
07 Aug, 2024
Given string str, the task is to check whether the given string is a valid domain name or not by using Regular Expression.
The valid domain name must satisfy the following conditions:
- The domain name should be a-z or A-Z or 0-9 and hyphen (-).
- The domain name should be between 1 and 63 characters long.
- The domain name should not start or end with a hyphen(-) (e.g. -geeksforgeeks.org or geeksforgeeks.org-).
- The last TLD (Top level domain) must be at least two characters and a maximum of 6 characters.
- The domain name can be a subdomain (e.g. write.geeksforgeeks.org).
Examples:
Input: str = "write.geeksforgeeks.org"
Output: true
Explanation:
The given string satisfies all the above mentioned conditions. Therefore, it is a valid domain name.
Input: str = "-geeksforgeeks.org"
Output: false
Explanation:
The given string starts with a hyphen (-). Therefore, it is not a valid domain name.
Input: str = "geeksforgeeks.o"
Output: false
Explanation:
The given string have last TLD of 1 character, the last TLD must be between 2 and 6 characters long. Therefore, it is not a valid domain name.
Input: str = ".org"
Output: false
Explanation:
The given string doesn't start with a-z or A-Z or 0-9. Therefore, it is not a valid domain name.
Approach: The idea is to use Regular Expression to solve this problem. The following steps can be followed to compute the answer:
- Get the String.
- Create a regular expression to check the valid domain name as mentioned below:
regex = "^((?!-)[A-Za-z0-9-]{1, 63}(?<!-)\\.)+[A-Za-z]{2, 6}$"
- Where:
- ^ represents the starting of the string.
- ( represents the starting of the group.
- (?!-) represents the string should not start with a hyphen (-).
- [A-Za-z0-9-]{1, 63} represents the domain name should be a-z or A-Z or 0-9 and hyphen (-) between 1 and 63 characters long.
- (?<!-) represents the string should not end with a hyphen (-).
- \\. represents the string followed by a dot.
- )+ represents the ending of the group, this group must appear at least 1 time, but allowed multiple times for subdomain.
- [A-Za-z]{2, 6} represents the TLD must be A-Z or a-z between 2 and 6 characters long.
- $ represents the ending of the string.
- Match the given string with the regular expression. In Java, this can be done by using Pattern.matcher().
- Return true if the string matches with the given regular expression, else return false.
Below is the implementation of the above approach:
C++
#include <iostream>
#include <regex>
using namespace std;
// Function to validate the domain name
bool isValidDomain(const string &str)
{
// Regex to check valid Domain Name
regex pattern("^[A-Za-z0-9-]{1,63}\\.[A-Za-z]{2,6}$");
// Return true if the string matches the regex
return regex_match(str, pattern);
}
// Driver Code
int main()
{
// Test Case 1:
string str1 = "geeksforgeeks.org";
cout << (isValidDomain(str1) ? "true" : "false") << endl;
// Test Case 2:
string str2 = "contribute.geeksforgeeks.org";
cout << (isValidDomain(str2) ? "true" : "false") << endl;
// Test Case 3:
string str3 = "-geeksforgeeks.org";
cout << (isValidDomain(str3) ? "true" : "false") << endl;
// Test Case 4:
string str4 = "geeksforgeeks.o";
cout << (isValidDomain(str4) ? "true" : "false") << endl;
// Test Case 5:
string str5 = ".org";
cout << (isValidDomain(str5) ? "true" : "false") << endl;
return 0;
}
Java
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class DomainValidator {
// Function to validate the domain name
public static boolean isValidDomain(String str)
{
// Regex to check valid Domain Name
String regex
= "^[A-Za-z0-9-]{1,63}\\.[A-Za-z]{2,6}$";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(str);
// Return true if the string matches the regex
return matcher.matches();
}
public static void main(String[] args)
{
// Test Case 1:
String str1 = "geeksforgeeks.org";
System.out.println(
isValidDomain(str1)); // Expected output: true
// Test Case 2:
String str2 = "contribute.geeksforgeeks.org";
System.out.println(
isValidDomain(str2)); // Expected output: true
// Test Case 3:
String str3 = "-geeksforgeeks.org";
System.out.println(
isValidDomain(str3)); // Expected output: false
// Test Case 4:
String str4 = "geeksforgeeks.o";
System.out.println(
isValidDomain(str4)); // Expected output: false
// Test Case 5:
String str5 = ".org";
System.out.println(
isValidDomain(str5)); // Expected output: false
}
}
Python
import re
# Function to validate the domain name
def is_valid_domain(s):
# Regex to check valid Domain Name
pattern = r"^[A-Za-z0-9-]{1,63}\.[A-Za-z]{2,6}$"
# Return true if the string matches the regex
return bool(re.match(pattern, s))
# Driver Code
# Test Case 1:
str1 = "geeksforgeeks.org"
print(is_valid_domain(str1)) # Expected output: True
# Test Case 2:
str2 = "contribute.geeksforgeeks.org"
print(is_valid_domain(str2)) # Expected output: True
# Test Case 3:
str3 = "-geeksforgeeks.org"
print(is_valid_domain(str3)) # Expected output: False
# Test Case 4:
str4 = "geeksforgeeks.o"
print(is_valid_domain(str4)) # Expected output: False
# Test Case 5:
str5 = ".org"
print(is_valid_domain(str5)) # Expected output: False
C#
using System;
using System.Text.RegularExpressions;
class DomainValidator {
// Function to validate the domain name
public static bool IsValidDomain(string str)
{
// Regex to check valid Domain Name
string pattern
= @"^[A-Za-z0-9-]{1,63}\.[A-Za-z]{2,6}$";
Regex regex = new Regex(pattern);
// Return true if the string matches the regex
return regex.IsMatch(str);
}
static void Main()
{
// Test Case 1:
string str1 = "geeksforgeeks.org";
Console.WriteLine(
IsValidDomain(str1)); // Expected output: True
// Test Case 2:
string str2 = "contribute.geeksforgeeks.org";
Console.WriteLine(
IsValidDomain(str2)); // Expected output: True
// Test Case 3:
string str3 = "-geeksforgeeks.org";
Console.WriteLine(
IsValidDomain(str3)); // Expected output: False
// Test Case 4:
string str4 = "geeksforgeeks.o";
Console.WriteLine(
IsValidDomain(str4)); // Expected output: False
// Test Case 5:
string str5 = ".org";
Console.WriteLine(
IsValidDomain(str5)); // Expected output: False
}
}
JavaScript
// JavaScript program to validate domain name using Regular
// Expression
// Function to validate the domain name
function isValidDomain(str)
{
// Regex to check valid Domain Name
let regex = /^[A-Za-z0-9-]{1,63}\.[A-Za-z]{2,6}$/;
// Check if the string is null or empty
if (!str) {
return "false";
}
// Return true if the string matches the regex
return regex.test(str) ? "true" : "false";
}
// Driver Code
// Test Case 1:
let str1 = "geeksforgeeks.org";
console.log(isValidDomain(str1)); // Expected output: true
// Test Case 2:
let str2 = "contribute.geeksforgeeks.org";
console.log(isValidDomain(str2)); // Expected output: true
// Test Case 3:
let str3 = "-geeksforgeeks.org";
console.log(isValidDomain(str3)); // Expected output: false
// Test Case 4:
let str4 = "geeksforgeeks.o";
console.log(isValidDomain(str4)); // Expected output: false
// Test Case 5:
let str5 = ".org";
console.log(isValidDomain(str5)); // Expected output: false
Outputtrue
false
true
false
false
Time Complexity: O(N) for each testcase, where N is the length of the given string.
Auxiliary Space: O(1)
Similar Reads
How to validate MAC address using Regular Expression Given string str, the task is to check whether the given string is a valid MAC address or not by using Regular Expression. A valid MAC address must satisfy the following conditions: It must contain 12 hexadecimal digits.One way to represent them is to form six pairs of the characters separated with
6 min read
How to validate ISIN using Regular Expressions ISIN stands for International Securities Identification Number. Given string str, the task is to check whether the given string is a valid ISIN(International Securities Identification Number) or not by using Regular Expression. The valid ISIN(International Securities Identification Number) must sati
6 min read
How to validate an IP address using Regular Expressions in Java Given an IP address, the task is to validate this IP address with the help of Regular Expressions.The IP address is a string in the form "A.B.C.D", where the value of A, B, C, and D may range from 0 to 255. Leading zeros are allowed. The length of A, B, C, or D can't be greater than 3.Examples: Inpu
3 min read
How to validate a Username using Regular Expressions in Java Given a string str which represents a username, the task is to validate this username with the help of Regular Expressions. A username is considered valid if all the following constraints are satisfied: The username consists of 6 to 30 characters inclusive. If the username consists of less than 6 or
3 min read
How to validate Indian driving license number using Regular Expression Given string str, the task is to check whether the given string is a valid Indian driving license number or not by using Regular Expression.The valid Indian driving license number must satisfy the following conditions: It should be 16 characters long (including space or hyphen (-)).The driving licen
7 min read
How to validate Indian Passport number using Regular Expression Given a string str of alphanumeric characters, the task is to check whether the given string is a valid passport number or not by using Regular Expression. A valid passport number in India must satisfy the following conditions: It should be eight characters long.The first character should be an uppe
5 min read
How to validate image file extension using Regular Expression Given string str, the task is to check whether the given string is a valid image file extension or not by using Regular Expression. The valid image file extension must specify the following conditions: It should start with a string of at least one character.It should not have any white space.It shou
5 min read
How to check Aadhaar number is valid or not using Regular Expression Given string str, the task is to check whether the given string is a valid Aadhaar number or not by using Regular Expression. The valid Aadhaar number must satisfy the following conditions: It should have 12 digits.It should not start with 0 and 1.It should not contain any alphabet and special chara
5 min read
Regular Expression to Validate a Bitcoin Address BITCOIN is a digital currency. During the digital currency transaction, a BTC address is required to verify the legality of a bitcoin wallet a Bitcoin address is a long set of alphanumeric characters that contains numbers and letters. A Bitcoin address indicates the source or destination of a Bitcoi
6 min read
Validate GIT Repository using Regular Expression GIT stands for GLOBAL INFORMATION TRACKER.Given some Git repositories, the task is to check if they are valid or not using regular expressions. Rules for the valid Git Repository are: It is an alphanumeric string containing uppercase Alphabet letters(A-Z) and digits(0-9).It should not contain any wh
5 min read