close
close
Regular Expression for Specific Hostnames (Perl) (removed duplicate)

Regular Expression for Specific Hostnames (Perl) (removed duplicate)

2 min read 09-11-2024
Regular Expression for Specific Hostnames (Perl) (removed duplicate)

When working with Perl, crafting a regular expression (regex) for specific hostnames can be essential for various applications, such as validating input, filtering data, or configuring server settings. Below, we will outline a regex pattern that matches certain hostname formats and provide guidance on how to implement it in Perl.

Understanding Hostname Structure

Before we create a regex, it's important to understand the components of a valid hostname:

  • Labels: Hostnames are composed of one or more labels separated by dots. Each label must start with a letter and may contain letters, digits, and hyphens.
  • Length: Each label must be between 1 to 63 characters, and the total hostname length should not exceed 253 characters.
  • Top-Level Domain (TLD): The last label must be a valid TLD, such as .com, .org, .net, etc.

Regular Expression Pattern

Here's a regex pattern tailored for matching specific hostnames in Perl:

my $regex = qr/^(?=.{1,253}$)(?=.{1,63}(?:\.[a-zA-Z]{2,})?$)(?!-)[A-Za-z0-9-]{1,63}(?<!-)(\.[A-Za-z0-9-]{1,63})*$/;

Explanation of the Regex Components

  • ^: Asserts the start of the string.
  • (?=.{1,253}$): Asserts that the total length is between 1 and 253 characters.
  • (?=.{1,63}(?:\.[a-zA-Z]{2,})?$): Asserts that the last segment of the hostname is a valid TLD of at least 2 characters.
  • (?!-): Negative lookahead to ensure the first character is not a hyphen.
  • [A-Za-z0-9-]{1,63}: Matches each label containing letters, digits, or hyphens, between 1 and 63 characters.
  • (?<!-): Negative lookbehind to ensure the last character of each label is not a hyphen.
  • (\.[A-Za-z0-9-]{1,63})*: Matches additional labels, ensuring they follow the same rules.
  • $: Asserts the end of the string.

Example Implementation in Perl

Here’s a simple Perl script demonstrating how to use the regex to validate hostnames:

use strict;
use warnings;

my @hostnames = (
    'example.com',
    'sub-domain.example.com',
    'invalid_hostname-.com',
    'another_invalid-.domain',
    'valid-hostname.net',
    '123.456.com'
);

foreach my $hostname (@hostnames) {
    if ($hostname =~ $regex) {
        print "$hostname is valid.\n";
    } else {
        print "$hostname is invalid.\n";
    }
}

Output

When you run the script, it will output whether each hostname is valid or invalid based on the specified criteria.

Conclusion

Using regular expressions in Perl to validate hostnames can greatly enhance your ability to filter and manage data effectively. The pattern provided can be adjusted to meet specific requirements depending on your needs. By understanding the structure of hostnames and how to craft regex patterns, you can ensure accurate hostname validation in your applications.

Popular Posts