Operating System - HP-UX
1827283 Members
3573 Online
109717 Solutions
New Discussion

Re: regular expression in perl

 
SOLVED
Go to solution
andi_1
Frequent Advisor

regular expression in perl

Hello,

I have the following format:

email address = email@email.com

Does anyone know how can I guarantee to retrieve email@email.com and assign it to a variable?

Thank you!
5 REPLIES 5
H.Merijn Brand (procura
Honored Contributor
Solution

Re: regular expression in perl

Can you elaborate on that question? If you just want to parse that line, it is something like

my ($address) = (m/email\s*address\s*=\s*(\S.*)/);
Enjoy, Have FUN! H.Merijn
andi_1
Frequent Advisor

Re: regular expression in perl

Hi,

Basically, my perl file will be feed a file, where I need to search for a specific field, email address:
the file will have email field formatted this way:
email address = email@email.com

here is my perl code:
while($line = )
{
if ($line =~ /^email address/)
{
my ($address) = (m/email\s*address\s*=\s*(\S.*)/);
print $address;
}
}

basically, $line will be "email address = email@email.com"

Than, I will need to basically, to parse $line and assign email value to a local variable.

I tried your way, but when I print $address, nothing is displayed.

Thanks for your help!
H.Merijn Brand (procura
Honored Contributor

Re: regular expression in perl

that's because my example uses the default buffer ($_), whereas you've read your line in $line. Go either way:

1---
while()
{
if (m/^email address/)
{
my ($address) = (m/email\s*address\s*=\s*(\S.*)/);
print $address;
}
}
---

or

2---
while($line = )
{
if ($line =~ /^email address/)
{
my ($address) = ($line =~ m/email\s*address\s*=\s*(\S.*)/);
print $address;
}
}
---

also possible:

3---
while()
{
if ($line =~ m/^email address = (.*)/)
{
my $address = $1;
print $address;
}
}
---

note also that your code is quite rigid with spaces. compare

m/^email address = (.*)/

to

m/\bemail\s+address\s*=\s*(\S.*)/
Enjoy, Have FUN! H.Merijn
andi_1
Frequent Advisor

Re: regular expression in perl

Thanks a lot for your help!

Here is what I have:

while($line = )
{
if ($line = m/^email address/)
{

my ($address) = ($line =~ m/\bemail\s+address\s*=\s(\S.*)/);
print $address;
}
}

my template contains the following line:

email address = lz@yahoo.com

For some reasons, print $address doesn't display anything. ;-(

Thanks again!
andi_1
Frequent Advisor

Re: regular expression in perl

Sorry, I had a typo!

Your example works fine!!

Thanks a lot!