gsub for string

R

Reinhart Viane

[Note: parts of this message were removed to make it a legal post.]

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!
 
R

Robert Klemme

2010/3/1 Reinhart Viane said:
I'm looking for a function that makes it possible to do the folowing:

Replace all =A0substrings --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

--=20
remember.guy do |as, often| as.you_can - without end
http://blog.rubybestpractices.com/
 
B

Brian Candler

Robert said:
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" }
 
R

Robert Klemme

2010/3/1 Brian Candler said:
Robert said:
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.
:)

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
 

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

Similar Threads

gsub with wildcard 6
gsub and backslashes 15
String#gsub escaping special characters 5
Tasks 1
Accessing local variables dynamically 1
'\\\\\\\\' madness? 3
place string into paste buffer? 4
String to Class 2

Members online

No members online now.

Forum statistics

Threads
474,262
Messages
2,571,049
Members
48,769
Latest member
Clifft

Latest Threads

Top