[英]Replace all words which don't match a RegExp pattern in Ruby
我在 ruby 中有一個字符串,比方說"hello, I am a string, I am surrounded by quotes"
我想替換所有與 RegExp 模式不匹配的單詞(以空格分隔),假設/.+?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
但是有更好的方法嗎? 因為對於一個相對簡單的操作來說,這是相當多的代碼。
s
開頭或結尾的單詞假設您的真正規則是排除以字符s
開頭或結尾的單詞,您可以拆分單詞,然后將 map String#gsub拆分到每個元素上。 例如,使用 Ruby 2.7.2+(我實際上使用的是 3.0.0-preview1):
str = "hello, i am a string, i am surrounded by quotes"
str.split.map { _1.gsub(/\b[^s]+\b/) { "foo" } }.join ?\s
#=> "foo, foo foo foo string, foo foo surrounded foo quotes"
這也適用於早期的 Ruby 版本。 只需將位置塊參數(例如_1
)替換為word之類的命名變量,並且(如果您願意)將簡寫?\s
替換為"\s"
。 例如,使用 Ruby 2.5.8:
str = 'hello, i am a string, i am surrounded by quotes'
str.split.map do |word|
word.gsub(/\b[^s]+\b/) { 'foo' }
end.join "\s"
#=> "foo, foo foo foo string, foo foo surrounded foo quotes"
結果應該是相同的兩種方式。
我說的是紅寶石弦"hello, I am a string, I am surrounded by quotes"
並且我想用/.+?s/
模式替換所有不匹配RegExp模式的單詞(用空格隔開),讓/.+?s/
說/.+?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
但是有更好的方法嗎? 因為對於一個相對簡單的操作來說,這是很多代碼。
從您的示例來看,您似乎想用'foo'
替換所有單詞,但包含's'
單詞除外; 即'string'
、 'surrounded'
和'quotes'
。 為此,您可以將/(.+)?s/
簡化為/s/
(例如, 'beeswax'.match?(/s/) #=> true
)。
最好在整個字符串上使用String#gsub ,因為它會保留單詞之間的額外空格。 如果改為在空格上拆分字符串,替換結果數組中的每個單詞,然后join
這些元素以形成一個新字符串,則多余的空格將被刪除。 例如,如果一個人是老式的,在句子之間插入兩個空格,我們可能有以下內容。
str = "Hello, I use a string of words, surrounded by quotes. So there."
並希望在結果字符串中保留句點后的兩個空格。 此外,拆分空格然后連接修改后的單詞會創建一個不必要的數組。
假設我們希望用'foo'
替換不包含匹配's'
或'S'
的單詞。 包含's'
或'S'
的單詞匹配正則表達式
r = /s/i
然后我們可以寫:
str.gsub(/\w+/) { |s| s.match?(r) ? s : 'foo' }
#=> "foo, foo use foo string foo words, surrounded foo quotes. So foo."
gsub
的參數是匹配單詞的正則表達式。
考慮第二個例子。 假設我們將所有既不以's'
或'S'
開頭也不以 'foo' 結尾的單詞替換為'foo'
; 也就是說,不匹配正則表達式的單詞
r = /\As|s\z/i
我們可以用同樣的方式做到這一點:
str.gsub(/\w+/) { |s| s.match?(r) ? s : 'foo' }
#=> "foo, foo foo foo string foo words, surrounded foo quotes. So foo."
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.