Ruby String 的 gsub 和 sub 方法之间的区别是什么

我今天仔细阅读了 String的文档,看到了 :sub方法,这是我以前从未注意到的。我一直在使用 :gsub,看起来它们本质上是一样的。有人能给我解释一下这其中的区别吗?谢谢!

56988 次浏览

g代表全球(global) ,代替全球(all) :

顺便说一句:

>> "hello".sub('l', '*')
=> "he*lo"
>> "hello".gsub('l', '*')
=> "he**o"

不同之处在于,sub只替换指定模式的第一个匹配项,而 gsub对所有匹配项都进行替换(即全局替换)。

value = "abc abc"
puts value                                # abc abc
# Sub replaces just the first instance.
value = value.sub("abc", "---")
puts value                                # --- abc
# Gsub replaces all instances.
value = value.gsub("abc", "---")
puts value                                # --- ---

subgsub分别替换第一个和所有匹配。

sub(pattern, replacement, x, ignore.case = FALSE, perl = FALSE,
fixed = FALSE, useBytes = FALSE)


gsub(pattern, replacement, x, ignore.case = FALSE, perl = FALSE,
fixed = FALSE, useBytes = FALSE)




sub("4", "8", "An Introduction to R Software Course will be of 4 weeks duration" )
##"An Introduction to R Software Course will be of 8 weeks duration"


gsub("4", "8", "An Introduction to R Software Course will be of 4 weeks duration" )
##"An Introduction to R Software Course will be of 8 weeks duration"