如何用星号替换字符串中数组元素匹配的子串(忽略大小写)
字符串内容模糊替换解决方案
问题说明
我有一个包含句子的字符串,以及一个存储若干单词的数组。需要检查该字符串中是否存在数组内的单词——甚至是数组单词作为字符串中单词的部分内容,且匹配时忽略大小写。若存在匹配项,需将对应内容替换为*****。尝试过any?、include?、gsub等方法,但未能实现预期效果,希望得到帮助。
示例代码
array = ['ga', 'day', 'sky'] string = "Peter went to the garden, to gather oranges. It was a sunny day and there were a lot of birds in the sky." array.each do |word| if string.include? (word) temp.gsub(word, "*****") # or temp[word] = "*****" end end
期望输出
Peter went to the *****, to ***** oranges. It was a sunny ***** and there were a lot of birds in the *****.
实现方案
你的代码存在两个核心问题:一是gsub不会直接修改原字符串,而是返回新字符串;二是没有处理忽略大小写和全局匹配的需求。用正则表达式结合gsub就能解决,代码如下:
array = ['ga', 'day', 'sky'] string = "Peter went to the garden, to gather oranges. It was a sunny day and there were a lot of birds in the sky." # 将数组单词合并为忽略大小写的正则模式 match_pattern = Regexp.union(array, Regexp::IGNORECASE) # 全局替换所有匹配内容为***** processed_string = string.gsub(match_pattern, "*****") puts processed_string
代码解析
Regexp.union(array, Regexp::IGNORECASE):把数组里的所有单词组合成一个正则表达式,同时开启忽略大小写模式,不管目标字符串里是Ga、GA还是ga,都会被匹配到。string.gsub(match_pattern, "*****"):gsub会全局替换所有符合正则的内容,返回替换后的新字符串,需要用变量接收结果(原字符串不会被修改)。
运行这段代码即可得到你想要的输出。
内容的提问来源于stack exchange,提问作者Elissei Hilakivi
相关产品推荐
相关产品推荐

