Another RegExp question


#1

Hi again, I’m allways here to ask how to use regular expressions.
what I want now is to replace chars from a string with empty spaces

sample = “thi’s is a tes<>%$#!|t”

what I want is use sample.sub([’<>%$#!|],"")
and the outcome shoudl be

“this is a test”

But I only can replace the first occurence of the chars specified in the
reg exp

How can I replace all occurences?

Thnaks,


#2

Hi –

On 3/18/07, J. mp removed_email_address@domain.invalid wrote:

But I only can replace the first occurence of the chars specified in the
reg exp

How can I replace all occurences?

Use gsub instead of sub.

David


#3

J. mp wrote:

what I want is use sample.sub([’<>%$#!|],"")

But I only can replace the first occurence of the chars specified in the
reg exp
How can I replace all occurences?

Use gsub instead of sub.


#4

On 3/18/07, J. mp removed_email_address@domain.invalid wrote:

How can I replace all occurences?

Thnaks,


Posted via http://www.ruby-forum.com/.

Will this work ?

sample = “thi’s is a tes<>%$###!!!###!|t”

x = sample.gsub(/[’’<>%$#!|]/,"")
puts x

Harry

http://www.kakueki.com/ruby/list.html
Japanese Ruby List Subjects in English


#5

On 18.03.2007 12:40, J. mp wrote:

But I only can replace the first occurence of the chars specified in the
reg exp

How can I replace all occurences?

You can find it in the docs: http://ruby-doc.org/

Hint: There are sub, sub!, gsub and gsub!.

Kind regards

robert


#6

On 3/18/07, J. mp removed_email_address@domain.invalid wrote:

How can I replace all occurences?

But, wouldn’t it be easier to do something like this?

sample = “thi’s is a tes<>%$###!!!###!|t”
y = sample.delete("#!%<’>$|")
puts y

Harry

http://www.kakueki.com/ruby/list.html
Japanese Ruby List Subjects in English


#7

If you want, you could tell gsub to replace everything that is not a-z
or A-Z or a white space character

sample = “thi’s is a tes<>%$#!|t”
sample.gsub(/[^a-zA-Z\s]/,"")
“this is a test”


#8

J. mp removed_email_address@domain.invalid wrote:

But I only can replace the first occurence of the chars specified in the
reg exp

How can I replace all occurences?

http://www.rubycentral.com/book/ref_c_string.html#String.gsub

Harry

http://www.kakueki.com/ruby/list.html
Japanese Ruby List Subjects in English