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

What is the difference between gsub and sub methods for Ruby Strings

今天,我一直在仔细阅读String的文档,并且看到了:sub方法,这是我以前从未注意到的方法。 我一直在使用:gsub,看来它们本质上是相同的。 谁能向我解释差异? 谢谢!


g代表全局,与全局替换(全部)相同:

在irb中:

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


区别在于sub仅替换指定模式的第一个匹配项,而gsub则针对所有匹配项进行替换(即,它全局替换)。


1
2
3
4
5
6
7
8
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分别替换第一个和所有匹配项。

1
2
3
4
5
6
7
8
9
10
11
12
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"