Ruby字符串中gsub方法和sub方法有什么区别?

127

今天我一直在阅读关于 String 的文档,看到了以前从未注意到的:sub方法。我一直使用:gsub,它们似乎基本相同。 有人能解释一下它们之间的区别吗? 谢谢!

我今天一直在研究关于字符串 String 的文档,发现了一个我之前没有注意到的方法 :sub。我一直在使用 :gsub,它们看起来基本相同。有人能告诉我它们之间的区别吗?谢谢!

5
http://ruby-doc.org/core/classes/String.html - mu is too short
4个回答

235

g代表全局替换,即替换全部:

在irb中:

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

16
好的,我明白了。就我的防御而言,我认为这一点并不是非常明显......直到现在才明白。 - Ryanmt
18
我同意你的看法,这并不明显!Java将它们称为replacereplaceAll。但是Ruby的根源可以追溯到使用g修饰符的Perl。这只是其中的一个事情。 - Ray Toal
1
幸运的是,现在很明显了。我将来会知道的。 - Ryanmt
顺便说一下,subgsub 快得多,这里有一个基准测试 https://github.com/JuanitoFatas/fast-ruby/blob/master/code/string/gsub-vs-sub.rb - blio
我发现这个问题的行为有所不同:=> " commas A, sentence, separated, by"``` 你们有什么想法,为什么使用正则表达式组时,`gsub!`似乎只能找到/替换第一个实例? - Bennett Talpers
显示剩余2条评论

41

区别在于sub只替换指定模式的第一个出现,而gsub会替换所有出现的模式(即全局替换)。


16
如果你早一分钟回答,也许就可以多获得1020点声望值。 :) - Andrew Grimm

5
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                                # --- ---

-1

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"

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接