Ruby使用带有正则表达式的gsub

时间:2016-12-09 03:11:39

标签: ruby regex gsub

好的,所以我尝试使用带有正则表达式的gsub来替换整个单词,而不是它的一部分。其中一条规则是改变" be"到b。但我只想为个别单词做这件事。

原始字符串:rvm

修改后的字符串:5.0.0.1

所需字符串:I really want to be the best at everything

以下代码将接受一个字符串数组,并且应该更改" be"到" b"。

I really want to be the best at everything

如果我在不使用正则表达式的情况下替换它,它会给我这个:I really want to b the best at everything

2 个答案:

答案 0 :(得分:2)

/\bword\b/查找单词word,而不是变量word定义的字符串。只需在代码中将此正则表达式更改为/\b#{pattern}\b/或可能/\b#{pattern}\b/i(不区分大小写),您的方法就可以正常工作。

此替代品输出一个新数组,而不更改原始数组:

def substitutor(strings,rules)
  rules.inject(strings) do |strings, (pattern, replace)|
    strings.map do |string|
      string.gsub(/\b#{pattern}\b/i, replace)
    end
  end
end

puts substitutor(array,rules)

# Hey guys, can anyone teach me how 2 b cool? 
# I really want 2 b the best @ everything,
# u know what I mean? Tweeting is super fun u guys!!!!
# OMG u guys, u won't believe how sweet my kitten is. 
# My kitten is like super cuddly & 2 cute 2 b believed right?
# I'm running out of example tweets 4 u guys, which is weird, 
# because I'm a writer & this is just writing & I tweet all day. 
# 4 real, u guys. 4 real.
# GUISEEEEE this is so fun! I'm tweeting 4 u guys & this tweet is 
# SOOOO long it's gonna b way more than u would think twitter can handle, 
# so shorten it up u know what I mean? I just can never tell how long 2 keep typing!
# New game. Middle aged tweet followed by #youngPeopleHashTag Example: 
# Gotta get my colonoscopy & mammogram soon. Prevention is key! #swag

答案 1 :(得分:0)

您可以按照以下方式执行此操作。

rules.default_proc = ->(_,k) { k }
arr = array.map { |s| s.gsub(/\w+/, rules) }

产生以下内容。

arr.each { |s| puts s }
  # Hey guys, can anyone teach me how 2 b cool? 
  # I really want 2 b the best @ everything,
  # u know what I mean? Tweeting is super fun u guys!!!!
  # OMG u guys, u won't believe how sweet my kitten is. 
  # My kitten is like super cuddly & 2 cute 2 b believed right?
  # I'm running out of example tweets 4 u guys, which is weird, 
  # because I'm a writer & this is just writing & I tweet all day. 
  # For real, u guys. For real.
  # GUISEEEEE this is so fun! I'm tweeting 4 u guys & this tweet is 
  # SOOOO long it's gonna b way more than u would think twitter can handle, 
  # so shorten it up u know what I mean? I just can never tell how long 2 keep typing!
  # New game. Middle aged tweet followed by #youngPeopleHashTag Example: 
  # Gotta get my colonoscopy & mammogram soon. Prevention is key! #swag

我使用Hash#default_proc=将proc附加到rules,以便rules[k]如果k没有密钥rulesk返回$ sudo chmod -R 777 /opt/jython/cachedir 使用String#gsub的形式,使用哈希进行替换。