【发布时间】:2020-10-25 17:09:43
【问题描述】:
我有一个 ruby 字符串,比如说"hello, I am a string, I am surrounded by quotes"
我想替换所有不匹配正则表达式模式的单词(用空格分隔),比如说/.+?s/ 和"foo"。
所以结果将是"foo foo foo foo string, foo foo surrounded foo quotes"
因为单词有分隔符我可以做
str = "hello, I am a string, I am surrounded by quotes"
str = str.split
str.each{
|e|
x = e.match(/(.+)?s/)
if x.to_s.empty? then e.replace "foo" end
}
str = str.join(" ")
puts str # -> foo foo foo foo string, foo foo surrounded foo quotes
但是有没有更好的方法呢?因为对于一个相对简单的操作来说,这是相当多的代码。
【问题讨论】:
标签: ruby