如何获得gsub!识别不同的字符(大写,小写)

How to get gsub! to recognize different characters (uppercase, lowercase)

print "Enter your text here:"
user_text = gets.chomp
user_text_2 = user_text.gsub! "Damn", "Darn"
user_text_3 = user_text.gsub! "Shit", "Crap"
puts "Here is your edited text: #{user_text}"

我希望当我使用 Shit 和 Damn 的小写版本并将它们替换为替代词时,该代码也能识别。现在它只能识别我输入首字母大写的单词。有什么办法让它也能识别小写单词,而无需添加更多 gsub!代码行?

只是一个非常简短的解决方案:

user_text.gsub!(/[Dd]amn/, 'Darn')

如果这是您想要的,更通用的方法是使用 i 使正则表达式不区分大小写。

user_text.gsub!(/damn/i, 'Darn')

您可以在 patten 上指定 i 标志以忽略大小写:

user_text_2 = user_text.gsub! /Damn/i, "Darn"

您可以使用 Regexp 和 i 选项来做到这一点,这使得 Regexp 不区分大小写:

foo = 'foo Foo'

foo.gsub(/foo/, 'bar')
#=> "bar Foo"
foo.gsub(/foo/i, 'bar')  # with i
#=> "bar bar"

使用正则表达式而不是字符串。所以 /damn/i 而不是 "damn". 正则表达式末尾的 'i' 表示忽略大小写。