Gsub for string

Hi,

I’m looking for a function that makes it possible to do the folowing:

Replace all substrings --xxxx-- with -xxxx–1 in a string.

The xxxx represents an unknown value (can be anything)

Is there a way to set unknow characters in a gsub function?

Thx!

2010/3/1 Reinhart V. [email protected]:

I’m looking for a function that makes it possible to do the folowing:

Replace all substrings --xxxx-- with -xxxx–1 in a string.

The xxxx represents an unknown value (can be anything)

Is there a way to set unknow characters in a gsub function?

You can match arbitrary characters and use capturing groups

str.gsub(/–([^-]+)–/, ‘-\1–1’)

Kind regards

robert

Robert K. wrote:

You can match arbitrary characters and use capturing groups

str.gsub(/–([^-]+)–/, ‘-\1–1’)

which you can also do in a block form, which is sometimes clearer and
lets you do things like modifying xxxx.

str.gsub(/–([^-]+)–/) { “-#{$1}–1” }

2010/3/1 Brian C. [email protected]:

Robert K. wrote:

You can match arbitrary characters and use capturing groups

str.gsub(/–([^-]+)–/, ‘-\1–1’)

which you can also do in a block form, which is sometimes clearer and
lets you do things like modifying xxxx.

str.gsub(/–([^-]+)–/) { “-#{$1}–1” }

For fairness reasons you should also mention that this is also slower
and not needed in this particular case since the replacement is fixed.
:slight_smile:

This is also a good opportunity to link to my most recent blog entry
which dealt with string replacements:

http://blog.rubybestpractices.com/posts/rklemme/020-Code_Massage.html

Cheers

robert

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs