【问题标题】:What is the difference between gsub and sub methods for Ruby StringsRuby字符串的gsub和sub方法有什么区别
【发布时间】:2011-07-20 18:45:48
【问题描述】:

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

【问题讨论】:

标签: ruby string


【解决方案1】:

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

在 irb 中:

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

【讨论】:

  • 是的。我现在知道了。在我的辩护中,我认为这不是很明显......直到现在,就是这样。
  • 我同意你的观点,这并不明显! Java 调用这些 replacereplaceAll。但是 Ruby 源于使用 g 修饰符的 Perl。这只是其中之一。
  • 幸运的是,现在很明显了。我以后会知道的。
  • 顺便说一句,subgsub 快很多,这里有一个基准github.com/JuanitoFatas/fast-ruby/blob/master/code/string/…
  • 我看到了一些不同的行为:A, sentence, separated, by, commas".gsub!(/(.*),(.*)/,"\\2 \\1") => " commas A, sentence, separated, by" 任何想法为什么gsub! 在使用正则表达式组时似乎只查找/替换第一个实例?
【解决方案2】:

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

【讨论】:

  • 如果您早一分钟回答,那么您的代表可能会多出 1020 个。 :)
【解决方案3】:
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                                # --- ---

【讨论】:

    【解决方案4】:

    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"
    

    【讨论】:

      猜你喜欢
      • 2015-01-01
      • 2012-04-09
      • 1970-01-01
      • 2012-04-28
      • 2010-10-11
      • 2011-12-21
      • 1970-01-01
      • 1970-01-01
      • 2011-11-13
      相关资源
      最近更新 更多