regex problem

E

eldwin

Hey all,

I'm trying to search and replace to the following string:

0|1061203|150200559802-12345|STUDIO
0006979867|STUDIO|0066678||STUDIO|150200559802-12345|STAFF|XX|STAFF|XX|

What I want to do is replace whatever is in between | |.

For example, I want to replace STAFF with PROSTAFF.

my current regex looks like this:

s/\|.*\|XX\|/\|PROSTAFF\|XX\|/g

So, I'm not concerned with STAFF so much, but what's in between | |. I
know "|" is a special character thus the "\" before it.

When I apply this regex to my code, the resulting string is:

0|PROSTAFF|XX|

Thanks in advance for any advice.
 
J

Josef Moellers

eldwin said:
Hey all,

I'm trying to search and replace to the following string:

0|1061203|150200559802-12345|STUDIO
0006979867|STUDIO|0066678||STUDIO|150200559802-12345|STAFF|XX|STAFF|XX|

What I want to do is replace whatever is in between | |.

For example, I want to replace STAFF with PROSTAFF.

my current regex looks like this:

s/\|.*\|XX\|/\|PROSTAFF\|XX\|/g

So, I'm not concerned with STAFF so much, but what's in between | |. I
know "|" is a special character thus the "\" before it.

When I apply this regex to my code, the resulting string is:

0|PROSTAFF|XX|

Thanks in advance for any advice.

You may want to take a look at Text::CSV_XS

use warnings;
use strict;
use Text::CSV_XS;

my $csv = Text::CSV_XS->new({sep_char => '|'});
die "failed to get new csv\n" unless $csv;
while (<STDIN>) {
chomp;
my $status = $csv->parse($_);
die "bad line $_\n" unless $status;
my @fields = $csv->fields();
foreach (@fields) {
$_ = "PROSTAFF" if $_ eq "STAFF";
}
$status = $csv->combine(@fields);
die "failed to combine ", join('|', @fields), "\n" unless $status;
print $csv->string(), "\n";

}
 
E

eldwin

0|PROSTAFF|XX|Another approach is to use split to break up your line into the
substrings that occur between pipe characters, modify every other
substring, and put the line back together (untested):

my @f = split(m{\|},$string);
for( my $i = 1; $i <= $#f; $i += 2 ) {
$f[$i] =~ s/^STAFF$/PROSTAFF/;
}
my $newstring = join('|',@f);

The split function did the trick. Thanks for your help.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,811
Messages
2,569,693
Members
45,478
Latest member
dontilydondon

Latest Threads

Top