标签:
# ruby的gsub字符串替换功能
1.可以使用hash来替换对应的字符串:
"hello 123 world".gsub(/hello|world/, ‘hello‘=>‘HELLO‘, ‘world‘=>‘WORLD‘) # => "HELLO 123 WORLD"
虽然支持第二个参数为hash,但不支持 symbol索引,即 hello: ‘HELLO‘, world: ‘WORLD‘ 无效
"hello 123 world".gsub(/hello|world/, hello: ‘HELLO‘, world: ‘WORLD‘) # => " 123 "
因为没有找到对应的索引,所以被替换成了空字符。
2.可以使用正则表达式替换字符串:
"hello 123 world".gsub /(\d+)/, ‘number‘ # => "hello number world"
3.可以使用 \1 \2 \n ... 来引用匹配的子串
"hello 123 world".gsub /(\d+)/, "(\\1)" # => "hello (123) world"
4.可以使用 block来处理匹配内容
"hello 123 world".gsub /(\d+)/ do |m| m.to_i + 1 end # => "hello 124 world"
5.多个匹配在block中的引用,无法通过多个block参数引用到,下面的写法无效:?
"His height is 175.00cm and weight 60.00kg.".gsub /(\d+\.\d+)(\w+)/ do |height, unit| "%g%s" % [height, unit] end
只有第一个参数完整匹配到了 175.00cm,而后面的参数都为nil:height => 175.00cm, unit => nil
正确?写法:
1.
"His height is 175.00cm and weight 60.00kg.".gsub /(\d+\.\d+)(\w+)/ do |matched| "%g%s" % [$1, $2] end # => "His height is 175cm and weight 60kg."
2.
"His height is 175.00cm and weight 60.00kg.".gsub /(\d+\.\d+)(\w+)/ do |matched| "%g%s" % [Regexp.last_match[1], Regexp.last_match[2]] end # => "His height is 175cm and weight 60kg."
标签:
原文地址:http://my.oschina.net/jsk/blog/486658