in reply to search and replace desired portion from a line
Another statement of the problem might be "after 'addr:0x', replace 1 or more hex digits (or maybe just a single '0'?) with a string from a variable". The s/// match pattern might be expressed as
(?<= addr:0x) # after a certain literal string
[[:xdigit:]]+ # 1 or more hex digits
(Update: See "(?<=pattern)" (and friends) in Extended Patterns, "Lookaround Assertions" subsection, in perlre; Looking ahead and looking behind in perlretut. See also POSIX Character Classes in perlrecharclass for [[:xdigit:]] and similar.)
c:\@Work\Perl\monks>perl -wMstrict -le "my $s = qq{0 (0) tracegen chn:req cmd:SDP_CMD_RDSIZED unit:0x10 addr: +0x0 len:0x3f vc:0 qospri:0 qosfw:0 strm:0x0 chain:0 io:0\n}; ;; my $address = '500000000'; ;; $s =~ s{ (?<= addr:0x) [[:xdigit:]]+ }{$address}xms; ;; my $expected = qq{0 (0) tracegen chn:req cmd:SDP_CMD_RDSIZED unit:0x1 +0 addr:0x500000000 len:0x3f vc:0 qospri:0 qosfw:0 strm:0x0 chain:0 io +:0\n}; print 's/// ok' if $s eq $expected; " s/// ok
If you have Perl version 5.10+, you can use the more flexible \K (see Extended Patterns) positive look-behind assertion operator:
$s =~ s{ addr:0x \K [[:xdigit:]]+ }{$address}xms;
This allows the positive look-behind pattern to be held in a variable and managed separately:
my $tag = qr{ addr:0x }xms;
$s =~ s{ $tag \K [[:xdigit:]]+ }{$address}xms;
(Update: The advantage of such separate management is that a more complex pattern may be built up:
my $tag = qr{ (?: addr | foo | bar) :0x }xms;)
Give a man a fish: <%-{-{-{-<
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: search and replace desired portion from a line (updated)
by syedasadali95 (Acolyte) on May 30, 2019 at 07:04 UTC |