rails字符串替换mgsub from ruby cookbook

4 篇文章 0 订阅
1 篇文章 0 订阅
Problem
You want to perform multiple, simultaneous search-and-replace operations on a string.

Solution
Use the Regexp.union method to aggregate the regular expressions you want to match into one big regular expression that matches any of them. Pass the big regular expression into String#gsub, along with a code block that takes a MatchData object. You can detect which of your search terms actually triggered the regexp match, and choose the appropriate replacement term:

        class String
          def mgsub(key_value_pairs=[].freeze)
            regexp_fragments = key_value_pairs.collect { |k,v| k }
            gsub(
Regexp.union(*regexp_fragments)) do |match|
              key_value_pairs.detect{|k,v| k =~ match}[1]
            end
          end
        end



Here's a simple example:

        "GO HOME!".mgsub([[/.*GO/i, 'Home'], [/home/i, 'is where the heart is']])
        # => "Home is where the heart is!"



This example replaces all letters with pound signs, and all pound signs with the letter P:

        "Here is number #123".mgsub([[/[a-z]/i, '#'], [/#/, 'P']])
        # => "#### ## ###### P123"



Discussion
The naive solution is to simply string together multiple gsub calls. The following examples, copied from the solution, show why this is often a bad idea:

        "GO HOME!".gsub(/.*GO/i, 'Home').gsub(/home/i, 'is where the heart is')
        # => "is where the heart is is where the heart is!"

        "Here is number #123".gsub(/[a-z]/i, "#").gsub(/#/, "P")
        # => "PPPP PP PPPPPP P123"



In both cases, our replacement strings turned out to match the search term of a later gsub call. Our replacement strings were themselves subject to search-and-replace. In the first example, the conflict can be fixed by reversing the order of the substitutions. The second example shows a case where reversing the order won't help. You need to do all your replacements in a single pass over the string.

The mgsub method will take a hash, but it's safer to pass in an array of key-value pairs. This is because elements in a hash come out in no particular order, so you can't control the order of substution. Here's a demonstration of the problem:

        "between".mgsub(/ee/ => 'AA', /e/ => 'E') # Bad code
        # => "bEtwEEn"

        "between".mgsub([[/ee/, 'AA'], [/e/, 'E']]) # Good code
        # => "bEtwAAn"



In the second example, the first substitution runs first. In the first example, it runs second (and doesn't find anything to replace) because of a quirk of Ruby's Hash implementation.

If performance is important, you may want to rethink how you implement mgsub. The more search and replace terms you add to the array of key-value pairs, the longer it will take, because the detect method performs a set of regular expression checks for every match found in the string.

See Also
Recipe 1.17, "Matching Strings with Regular Expressions"

Confused by the *regexp_fragments syntax in the call to Regexp.union? Take a look at Recipe 8.11, "Accepting or Passing a Variable Number of Arguments"
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值