The following isn't efficient because it keeps re-matching the entire string, but this won't matter unless your strings are very long. It is simple.
#! /usr/local/bin/perl use strict; use warnings; my $str = "word1, word2, #18abcdefgh ,word4, #24qwer, word5"; print "Before: $str\n"; while($str =~ m/(.*?)#(\d)(\d)(.*)/) { $str = $1 . "<Binary block($2): $3 bytes>" . substr($4, $3); } print "After: $str\n";
Which produces:
Before: word1, word2, #18abcdefgh ,word4, #24qwer, word5 After: word1, word2, <Binary block(1): 8 bytes> ,word4, <Binary block +(2): 4 bytes>, word5
I wondered about the first digit after the '#' so I captured that and put it into the substitution also.
update: removed unnecessary capture from the RE.
update2: A better alternative and comparison:
#! /usr/local/bin/perl use strict; use warnings; use Benchmark qw(cmpthese); my $str = "word1, word2, #18abcdefgh ,word4, #24qwer, word5"; print "Before: $str\n"; while($str =~ m/#(\d)(\d)/g) { substr($str, pos($str) - 3, $2 + 3, "<Binary block($1): $2 bytes>" +); } print "After: $str\n"; my $start = "word1, word2, #18abcdefgh ,word4, #24qwer, word5"; print "\n\n"; cmpthese( -10, { 're-match whole string' => sub { my $str = $start; while($str =~ m/(.*?)#(\d)(\d)(.*)/) { $str = $1 . "<Binary block($2): $3 bytes>" . substr($4 +, $3); } }, 'match #\d\d' => sub { my $str = $start; while($str =~ m/#(\d)(\d)/g) { substr($str, pos($str) - 3, $2 + 3, "<Binary block($1) +: $2 bytes>"); } }, }, );
Before: word1, word2, #18abcdefgh ,word4, #24qwer, word5 After: word1, word2, <Binary block(1): 8 bytes> ,word4, <Binary block +(2): 4 bytes>, word5 Rate re-match whole string match # +\d\d re-match whole string 75230/s -- +-28% match #\d\d 104315/s 39% + --
In reply to Re: Can I use backreferences as quantifiers in a regex?
by ig
in thread Can I use backreferences as quantifiers in a regex?
by johnbo
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |