ruby如何完成这个任务(在ruby中不区分大小写的字符串搜索和替换)?

时间:2021-09-15 19:26:03

I have some problem with replace string in Ruby.

在Ruby中替换字符串有一些问题。

My Original string : What the human does is not like what animal 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.

我在使用gsub时遇到了区分大小写的问题。(如。我想保留原文。

any solution?

有解决方案吗?

4 个解决方案

#1


20  

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.

如:人所做的事不象动物所做的事。

#2


3  

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.

到目前为止,在所有的3个答案中,最重要的是在正则表达式中使用“i”修饰符。这是指定Regexp: IGNORECASE选项使用的简写方法。

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

这里有一个非常有用的Ruby Regexp教程,这个类在这里有文档说明

#3


2  

Use the block form of gsub.

使用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."

#4


2  

another version without brackets () in regex,

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.

如:人所做的事不象动物所做的事。

#1


20  

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.

如:人所做的事不象动物所做的事。

#2


3  

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.

到目前为止,在所有的3个答案中,最重要的是在正则表达式中使用“i”修饰符。这是指定Regexp: IGNORECASE选项使用的简写方法。

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

这里有一个非常有用的Ruby Regexp教程,这个类在这里有文档说明

#3


2  

Use the block form of gsub.

使用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."

#4


2  

another version without brackets () in regex,

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.

如:人所做的事不象动物所做的事。