Double characters in string

W

Wouss Bla

Hi,

I'm looking for a way to put a 'X' between all double characters in a
string. So if this would be the string: 'hello, I just said hello' would
be changed into 'helXlo, I just said helXlo'.

I tried:

text = text.sub(/([a-z])\1/,'\1x\1')

But this only changed the first double character...

Thanks in advance
 
J

Jesús Gabriel y Galán

Hi,

I'm looking for a way to put a 'X' between all double characters in a
string. So if this would be the string: 'hello, I just said hello' would
be changed into 'helXlo, I just said helXlo'.

I tried:

text = text.sub(/([a-z])\1/,'\1x\1')

But this only changed the first double character...

From ri:

------------------------------------------------------------- String#sub
str.sub(pattern, replacement) => new_str
str.sub(pattern) {|match| block } => new_str
------------------------------------------------------------------------
Returns a copy of _str_ with the _first_ occurrence of _pattern_
replaced with either _replacement_ or the value of the block.

So it only replaces the first occurrence. Try gsub:

------------------------------------------------------------ String#gsub
str.gsub(pattern, replacement) => new_str
str.gsub(pattern) {|match| block } => new_str
------------------------------------------------------------------------
Returns a copy of _str_ with _all_ occurrences of _pattern_
replaced with either _replacement_ or the value of the block


irb(main):001:0> "hello, I said hello".gsub(/([a-z])\1/,'\1x\1')
=> "helxlo, I said helxlo"

Jesus.
 

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,770
Messages
2,569,583
Members
45,075
Latest member
MakersCBDBloodSupport

Latest Threads

Top