[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

use reqex to get the middle character and repeat it

Adam Akhtar

3/13/2008 9:16:00 PM

say i have the string "qxq" and i want to repeat the middle char 4 times
i could do this
str = "qxq
newstring = str.gsub(/(x)/, '\1'*4)

but if i have a string full of x's i.e. "xxx"
then it will repeat all of them 4 times and thats not what i want to
do...i just want the middle one to be repeated.

How do i alter that regex to do this???
--
Posted via http://www.ruby-....

1 Answer

Sebastian Hungerecker

3/13/2008 9:43:00 PM

0

Adam Akhtar wrote:
> say i have the string "qxq" and i want to repeat the middle char 4 times
> i could do this
> str = "qxq
> newstring = str.gsub(/(x)/, '\1'*4)
>
> but if i have a string full of x's i.e. "xxx"
> then it will repeat all of them 4 times and thats not what i want to
> do...i just want the middle one to be repeated.
>
> How do i alter that regex to do this???

str.gsub(/(\w)(x)(\w)/, '\1'+'\2'*4+'\3')

HTH,
Sebastian
--
Jabber: sepp2k@jabber.org
ICQ: 205544826