Regex: changing longer patterns to shorter ones

S

Steventangle

ITEM 0

How does one go about changing a longer pattern to a shorter one? For
instance, I try

$string =~ tr/longer/short/;

but it doesn't change "This is a longer pattern." to "This is a short
pattern." Rather, it does a one-for-one replacement yielding "This is a
shortr pattrro."

ITEM 1

How do you use variables in regexes? For instance, if I wanted to replace
the variable $var with $string, what's the tr or s syntax for it?

Thanks for the help,
Steve
 
G

Gunnar Hjalmarsson

Steventangle said:
How does one go about changing a longer pattern to a shorter one? For
instance, I try

$string =~ tr/longer/short/;

but it doesn't change "This is a longer pattern." to "This is a short
pattern."

Not surprising, since you are using the tr/// operator, which doesn't
include any pattern or regular expression.
Rather, it does a one-for-one replacement yielding "This is a
shortr pattrro."

Yep, that's what the tr/// operator does.

Try the s/// operator instead.

perldoc perlop
How do you use variables in regexes? For instance, if I wanted to replace
the variable $var with $string, what's the tr or s syntax for it?

s/$var/$string/

perldoc perlop
 
T

Tad McClellan

Steventangle said:
How do you use variables in regexes?


The same way that you use them in double quoted strings.

For instance, if I wanted to replace
the variable $var with $string, what's the tr or s syntax for it?


Show us what you have tried and we will help you fix it.
 
C

Chris Mattern

Steventangle said:
ITEM 0

How does one go about changing a longer pattern to a shorter one? For
instance, I try

$string =~ tr/longer/short/;

but it doesn't change "This is a longer pattern." to "This is a short
pattern." Rather, it does a one-for-one replacement yielding "This is a
shortr pattrro."

That's correct. That's what tr/// does. What you want is s///
ITEM 1

How do you use variables in regexes? For instance, if I wanted to replace
the variable $var with $string, what's the tr or s syntax for it?

You type $var right into the regex. It does interpolate, you know.
Thanks for the help,
Steve

--
Christopher Mattern

"Which one you figure tracked us?"
"The ugly one, sir."
"...Could you be more specific?"
 
S

StevenTangle

Yes, Gunnar, you were right on the money. Converting a longer string to a
shorter string became very easy after I used s/longer/short as
tr/longer/short does a one-to-one replacement of the letters. Also,
s/$var/$string works fines.

Thanks!
Steve
 

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

Forum statistics

Threads
473,774
Messages
2,569,596
Members
45,138
Latest member
NevilleLam
Top