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: Beginner:
regex/substitution on multiple cases

 



joseph4325
Novice

Jul 15, 2013, 9:49 AM

Post #1 of 6 (475 views)
regex/substitution on multiple cases Can't Post

my $names = "Bill and Steve and Jeff"

The goal is to do a substitution on this line that does the following:
1. s/Bill/Bob/ and s/Jeff/Jim/
2. substitute any character that does not match "Bill" or "Jeff" and replace with nothing.

Desired output: "BobJim"

I can do the first part, but not the 2nd.


Laurent_R
Veteran / Moderator

Jul 15, 2013, 10:39 AM

Post #2 of 6 (472 views)
Re: [joseph4325] regex/substitution on multiple cases [In reply to] Can't Post

One of many ways to do it (under the Perl debugger):


Code
  DB<36> $names = "Bill and Steve and Jeff" 

DB<37> $names =~ s/Bill/Bob/

DB<38> $names =~ s/Jeff/Jim/

DB<39> p $names
Bob and Steve and Jim
DB<40> $names =~ s/(Bob).*(Jim)/$1$2/

DB<41> p $names
BobJim
DB<42>



joseph4325
Novice

Jul 15, 2013, 10:49 AM

Post #3 of 6 (471 views)
Re: [Laurent_R] regex/substitution on multiple cases [In reply to] Can't Post

Thank you for the quick response. this worked perfectly.


BillKSmith
Veteran

Jul 15, 2013, 11:38 AM

Post #4 of 6 (467 views)
Re: [joseph4325] regex/substitution on multiple cases [In reply to] Can't Post

It can be done all at once. (I do not see an advantage to either method.)

Code
use strict; 
use warnings;
my $names = "Bill and Steve and Jeff" ;
my %sub = (Bill=>'Bob', Jeff=>'Jim');
$names =~ s/.*(Bill|Jeff).*(Bill|Jeff).*/$sub{$1}$sub{$2}/;
print $names, "\n";

Good Luck,
Bill


2teez
Novice

Jul 15, 2013, 1:08 PM

Post #5 of 6 (463 views)
Re: [joseph4325] regex/substitution on multiple cases [In reply to] Can't Post

You can simply replace all the string like so:

Code
use warnings; 
use strict;

my $names = "Bill and Steve and Jeff";

$names =~ s/.*/BobJim/;

print $names, $/;



Laurent_R
Veteran / Moderator

Jul 15, 2013, 1:57 PM

Post #6 of 6 (458 views)
Re: [2teez] regex/substitution on multiple cases [In reply to] Can't Post

Yeah, sure, you can also do this:


Code
my $names = "Bill and Steve and Jeff";  
print "BobJim\n";


My first idea was to reply with the above, but I quickly decided to try to be more helpful.

If the instructor sees only the execution but not the code, it should yield a good mark.

 
 


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

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