Thursday 26 January 2017

Perl script to check valid email addresses

Confirming if an email address is valid or not is a common practice in various website forms we fill out. In this article I'd like to share a quick perl script which checks if an entered email address is valid or not. We'll be using grouping along with regular expressions.

An email address should basically comprise of an alphanumeric string with the @ and . characters in it to signify the email address provider & top level domain name. The script I'll share will check for these conditions.

Given below is the script:

[root@alive ~]# cat hello.pl
#!/usr/bin/perl

use warnings;
use strict;

sub main {
        my @add = ("sa789\@gmail.com",
                   "john22.com",
                   "bond24\@yahoo.com",
                   "bond24\@yahoo");

        while (my $adr = <@add>) {
                if ($adr =~ /(\w+\@\w+\.\w+)/) { print "$1 \n\n" ; }
                }

        }

main();


When I run the script, the valid email addresses are printed out.

[root@alive ~]# ./hello.pl
sa789@gmail.com

bond24@yahoo.com


Let's describe the condition responsible for filtering the email addresses i.e. (\w+\@\w+\.\w+)
The brackets () indicate a grouping. The \w indicates the presence of an alphanumeric character. The plus symbol + indicates the presence of one or more such alphanumeric characters. The @ symbol represents the @ symbol in the email addresses and has to be escaped by a backslash \ sine we want to use the literal meaning of the symbol. In a similar fashion we escape the dot . symbol as well by a backslash.
Finally, we print the result of the group regular expression match by printing $1.

I hope this article has been an informative read & might give ideas for more use cases on regular expressions.

No comments:

Post a Comment

Using capture groups in grep in Linux

Introduction Let me start by saying that this article isn't about capture groups in grep per se. What we are going to do here with gr...