Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations bkrike on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

advanced (?) search and replace in perl 1

Status
Not open for further replies.

LeukvoorJ

Programmer
Jun 6, 2006
5
NL
I would like to find all the double letters in a string and replace them with the same letter + another character. I tried:

$string =~ s/.{2}/.2/gi;

But that doesn't work. I want to f.e. 'll' to become 'l2'. Can that be easily done?

Thanks in advance,

J
 
Yes,

Code:
echo "The tree fell onto the log" | perl -lne 's/(.)\1/${1}2/g;print'



Trojan.
 
I copy pasted it in windows cmd.exe but I don't see anything...?
 
Windoze?
That was for a Unix or Linux.
Suffice to say that the regex is the bit you need.
To make it look like your sample:
Code:
$string =~ s/(.)\1/${1}2/gi;

BTW: Do you really need it to be case insensitive?


Trojan.
 
Ah thanks. I don't specifically need the case insensitivity. I'll try it with and without.
 
Do you need it to only ever handle 2 or would it be better if it could put the quantity after the letter?

Try this for size!

Code:
$string =~ s/((.)\2+)/"$2" . length($1)/ge;


Trojan.
 
Your simpler one worked! Thanks! The more complex one didn't but it doesn't matter, I'm very happy it works. Thanks!

J
 
Just text in the string. I'll check it out later, I've got other thing to do at this moment. But thanks for your help.
 
Nice solution, Trojan. have a star!

Steve

[small]"Every program can be reduced by one instruction, and every program has at least one bug. Therefore, any program can be reduced to one instruction which doesn't work." (Object::perlDesignPatterns)[/small]
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top