[lnkForumImage]
TotalShareware - Download Free Software

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


 

Forums >

comp.lang.ruby

Double characters in string

Wouss Bla

11/5/2008 7:54:00 AM

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
--
Posted via http://www.ruby-....

1 Answer

Jesús Gabriel y Galán

11/5/2008 8:44:00 AM

0

On Wed, Nov 5, 2008 at 8:53 AM, Wouss Bla <wvdongen@zonnet.nl> wrote:
> 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.