use reqex to get the middle character and repeat it

A

Adam Akhtar

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???
 
S

Sebastian Hungerecker

Adam said:
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
 
A

Adam Akhtar

ahh why didnt i just think of that... str.gsub(/(\w)(x)(\w)/,
'\1'+'\2'*4+'\3')

In this situation the string will always be 3 chars long and will either
consist of spaces or x so the above will be fine (with a bit of
tweaking).

Thanks very much!
 
P

Peña, Botp

IyBJbiB0aGlzIHNpdHVhdGlvbiB0aGUgc3RyaW5nIHdpbGwgYWx3YXlzIGJlIDMgY2hhcnMgbG9u
ZyBhbmQgDQoNCnRoaXMgaXMgbm90IHJlZ2V4IDopDQoNCmlyYihtYWluKTowMDc6MD4gUlVCWV9W
RVJTSU9ODQo9PiAiMS45LjAiDQppcmIobWFpbik6MDA4OjA+IHN0cj0ncXhxJw0KPT4gInF4cSIN
CmlyYihtYWluKTowMDk6MD4gc3RyWzBdK3N0clsxXSo0K3N0clsyXQ0KPT4gInF4eHh4cSINCg0K
b3IgbW9yZSBzdWNjaW5jdCwNCg0KaXJiKG1haW4pOjAxMDowPiBzdHJbMV0qPTQNCj0+ICJ4eHh4
Ig0KaXJiKG1haW4pOjAxMTowPiBzdHINCj0+ICJxeHh4eHEiDQoNCg0Ka2luZCByZWdhcmRzIC1i
b3RwDQo=
 

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
474,285
Messages
2,571,416
Members
48,107
Latest member
AmeliaAmad

Latest Threads

Top