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

pgvzfuti  于 2023-01-25  发布在  Ruby
关注(0)|答案(4)|浏览(299)

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

bgtovc5b

bgtovc5b1#

g代表全局,如替换全局(全部):
IRB中:

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

2ic8powd2#

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

4szc88ey

4szc88ey3#

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

jc3wubiy4#

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"

相关问题