Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl: the Markov chain saw
 
PerlMonks  

Answer: How do i find $a and replace it with $b when it's preceded by $c?

( #302823=categorized answer: print w/ replies, xml ) Need Help??

Q&A > regular expressions > How do i find $a and replace it with $b when it's preceded by $c? contributed by Roy Johnson

If $c is actually a pattern, you should use the lookbehind. If you're just dealing with strings, the fastest might be some work with substr/index.
use Benchmark; use vars qw/$a $b $c/; ($a, $b, $c) = qw/bar baz foo/; timethese(shift || 500000, { lookbehind => sub { local $_ = "foobarquux"; s/(?<=$c)$a/$b/g +}, chromatic => sub { local $_ = "foobarquux"; s/($c)$a/$1$b/g +}, chromatic2 => sub { local $_ = "foobarquux"; s/$c$a/$c$b/g }, substr => sub { local $_ = "foobarquux"; while ((my $p = index($_, "$c$a"))>=0) { substr($_, $p+length($c), length($a), $b); } }, });
Output:
chromatic: 11 wallclock secs (10.67 usr + 0.00 sys = 10.67 CPU) @ 46 +860.36/s (n=500000) chromatic2: 10 wallclock secs ( 8.81 usr + 0.00 sys = 8.81 CPU) @ 56 +753.69/s (n=500000) lookbehind: 10 wallclock secs ( 9.42 usr + 0.00 sys = 9.42 CPU) @ 53 +078.56/s (n=500000) substr: 4 wallclock secs ( 3.98 usr + 0.00 sys = 3.98 CPU) @ 12 +5628.14/s (n=500000)

Comment on Answer: How do i find $a and replace it with $b when it's preceded by $c?
Select or Download Code
Log In?
Username:
Password:

What's my password?
Create A New User
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others studying the Monastery: (5)
As of 2014-12-27 05:25 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    Is guessing a good strategy for surviving in the IT business?





    Results (176 votes), past polls