CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

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

Post #1 of 4 (4773 views)
HELP!!Regex to match boundary from a range and substitute characters Can't Post

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

Post #2 of 4 (4752 views)
Re: [akshay34] HELP!!Regex to match boundary from a range and substitute characters [In reply to] Can't Post

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

Post #3 of 4 (4751 views)
Re: [Laurent_R] HELP!!Regex to match boundary from a range and substitute characters [In reply to] Can't Post

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

Post #4 of 4 (4744 views)
Re: [BillKSmith] HELP!!Regex to match boundary from a range and substitute characters [In reply to] Can't Post

Thanks a lot Bill you're a savior Smile

 
 


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives