开发者

How can ruby do this task (Case-insensitive string search & replace in Ruby)?

I have some problem with replace string in Ruby.

My Original string : What the human does is not like what animal开发者_Python百科 does.

I want to replace to: ==What== the human does is not like ==what== animal does.

I face the problem of case sensitive when using gsub. (eg. What , what) I want to keep original text.

any solution?


If I understood you correctly this is what you want to do:

puts "What the human does is not like what animal does.".gsub(/(what)/i, '==\1==')

which will output

==What== the human does is not like ==what== animal does.


another version without brackets () in regex,

puts "What the human does is not like what animal does.".gsub(/what/i,'==\0==')

==What== the human does is not like ==what== animal does.


The important thing to take account of in all 3 answers so far, is the use of the "i" modifier on the regular expression. This is the shorthand way to specify the use of the Regexp::IGNORECASE option.

A useful Ruby Regexp tutorial is here and the class is documented here


Use the block form of gsub.

"What the human does is not like what animal does.".gsub(/(what)/i) { |s| "==#{s}==" }
=> "==What== the human does is not like ==what== animal does."
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜