Replace exactly match of a number

T

Tambaa Hapa

I am trying to replace a number with some string. For example, replace &1
with hello. However using s/&$num/hello/g where $num = 1 also replaces &10
to hello0. Anyone have any ideas on how to do this?

Thanks in advance
TH
 
A

A. Sinan Unur

I am trying to replace a number with some string. For example, replace
&1 with hello. However using s/&$num/hello/g where $num = 1 also
replaces &10 to hello0. Anyone have any ideas on how to do this?

Isn't it a little too tedious to write your own templating system?
 
D

Dave Weaver

Tambaa Hapa said:
I am trying to replace a number with some string. For example, replace &1
with hello. However using s/&$num/hello/g where $num = 1 also replaces &10
to hello0. Anyone have any ideas on how to do this?

s/&$num(?!\d)/hello/g;

see "perldoc perlre" for details.
 
P

Paul Lalli

Tambaa said:
I am trying to replace a number with some string. For example, replace &1
with hello. However using s/&$num/hello/g where $num = 1 also replaces &10
to hello0. Anyone have any ideas on how to do this?

How about making sure the next thing is not a digit?

s/&$num(?!\d)/hello/g;

Read more about look-ahead assertions in:
perldoc perlre
perldoc perlretut
and probably one or two others I'm forgetting.

Paul Lalli
 
T

Tambaa Hapa

Thanks a bunch Dave. That certainly did the trick. I guess I just needed a
little imagination!

TH
 
T

Tambaa Hapa

Thanks Paul. I could not figure out how to do the look ahead. I tried
something like s/&$num[^\d]/hello/g but that replaced the next character
too, which is not what I wanted. Your suggestion (and Dave's) did the trick.
Thanks again.

TH
 
E

Eric Bohlman

Thanks Paul. I could not figure out how to do the look ahead. I tried
something like s/&$num[^\d]/hello/g but that replaced the next
character too, which is not what I wanted. Your suggestion (and
Dave's) did the trick. Thanks again.

I would, though, seriously take up Sinan's suggestion and go over to
http://search.cpan.org and search for "template"; there are tons of
excellent template-substitution modules and you might save yourself hours
of wheel-reinvention.
 

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,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top