Home: Perl Programming Help: Regular Expressions:
HELP!!Regex to match boundary from a range and substitute characters



akshay34
New User

Sep 17, 2012, 10:05 AM


Views: 11437
HELP!!Regex to match boundary from a range and substitute characters

Hi guys I am a beginner and I need help with this problem.

I am trying to this question.

Search for all names which second character of their first name is in the range of a-i. And it will substitute all beginning Lís with Zís.

The file is entered into an empty array from the command line. My problem is that I cant seem to devise a way to get the proper regex into the if statement.

Here is the code i have so far.

Here is the file containing text that is read into the empty array.

Joshua Smith
John Jenkins
Larry Roberts
Bob Jones
Linda Green
Tim Anderson
Adam Jackson


Code
#!/usr/bin/perl 

@phone = (<>);

foreach $item (@phone)
{
if ($item =~ /([a-i])\b/)
{
print $item;
}
}


Thanks for any help in advance =)


(This post was edited by akshay34 on Sep 17, 2012, 10:06 AM)


Laurent_R
Veteran / Moderator

Sep 17, 2012, 7:50 PM


Views: 11416
Re: [akshay34] HELP!!Regex to match boundary from a range and substitute characters

If you want to substitute only for those first names where the second range is in the specified range, try this:


Code
#!/usr/bin/perl 

use strict;
use warnings;

my @phone = (<>);

foreach my $item (@phone) {
s/^L([a-i]+.*)/Z$1/i;
print $item;
}


This will print all items, after having modified those matrching the pattern.


BillKSmith
Veteran

Sep 17, 2012, 8:14 PM


Views: 11415
Re: [Laurent_R] HELP!!Regex to match boundary from a range and substitute characters

Replace a leading 'L' with a 'Z' only if it is followed by any character in the range [a-i]. (Refer to documentation for zero-width positive lookahead assertion.) Print successful substitutions.

Code
use strict; 
use warnings;
my @phone = <DATA>;
print grep {s/^L(?=[a-i])/Z/} @phone;
__DATA__
Joshua Smith
John Jenkins
Larry Roberts
Bob Jones
Linda Green
Tim Anderson
Adam Jackso


Consider using a one-liner.

Code
perl -pe"$_=q() unless s/^L(?=[a-i])/Z/" names.dat

Note: Quoting is for windows. You may have to replace double quotes with single quotes.
Good Luck,
Bill

(This post was edited by BillKSmith on Sep 17, 2012, 8:33 PM)


akshay34
New User

Sep 17, 2012, 9:11 PM


Views: 11408
Re: [BillKSmith] HELP!!Regex to match boundary from a range and substitute characters

Thanks a lot Bill you're a savior Smile