Ruby multiple string replacement

后端 未结 7 1253
遇见更好的自我
遇见更好的自我 2020-12-02 07:17
str = \"Hello☺ World☹\"

Expected output is:

\"Hello:) World:(\"

I can do this: str.gsub(\"☺\", \":)\").gsu

7条回答
  •  爱一瞬间的悲伤
    2020-12-02 08:06

    Set up a mapping table:

    map = {'☺' => ':)', '☹' => ':(' }
    

    Then build a regex:

    re = Regexp.new(map.keys.map { |x| Regexp.escape(x) }.join('|'))
    

    And finally, gsub:

    s = str.gsub(re, map)
    

    If you're stuck in 1.8 land, then:

    s = str.gsub(re) { |m| map[m] }
    

    You need the Regexp.escape in there in case anything you want to replace has a special meaning within a regex. Or, thanks to steenslag, you could use:

    re = Regexp.union(map.keys)
    

    and the quoting will be take care of for you.

提交回复
热议问题