ruby string replace

在IRB(Interactive Ruby)中,你可以使用以下方法来替换字符串:

1.使用split,然后使用“#{}”(根据情况使用)

" now's  the time".split        #=> ["now's", "the", "time"],
" now's  the time".split(' ')   #=> ["now's", "the", "time"]
" now's  the time".split(/ /)   #=> ["", "now's", "", "the", "time"]
"1, 2.34,56, 7".split(%r{,\s*}) #=> ["1", "2.34", "56", "7"]
"hello".split(//)               #=> ["h", "e", "l", "l", "o"]
"hello".split(//, 3)            #=> ["h", "e", "llo"]
"hi mom".split(%r{\s*})         #=> ["h", "i", "m", "o", "m"]

"mellow yellow".split("ello")   #=> ["m", "w y", "w"]
"1,2,,3,4,,".split(',')         #=> ["1", "2", "", "3", "4"]
"1,2,,3,4,,".split(',', 4)      #=> ["1", "2", "", "3,4,,"]
"1,2,,3,4,,".split(',', -4)     #=> ["1", "2", "", "3", "4", "", ""]

"1:2:3".split(/(:)()()/, 2)     #=> ["1", ":", "", "", "2:3"]

"".split(',', -1)               #=> []

2.使用sub

var1 = "hello world"

var1.sub(/\w+lo/, "hey")

output:

"hey world"

3.如果是多处替换,使用gsub

var = "hello world"

=> "hello world"

irb(main):006:0>  var.gsub(/\bhello\b/, "Hello")

=> "Hello world"
string = "Hello, World!"
new_string = string.gsub("Hello", "Hi")
puts new_string
# 输出: Hi, World!

  使用正则表达式替换:你也可以使用正则表达式来替换字符串中的内容。 

string = "Hello, World!"
new_string = string.gsub(/Hello/, "Hi")
puts new_string
# 输出: Hi, World!

4.insert

msg = "Hello world"

=> "Hello world"

irb(main):008:0>  msg.insert 5, ","

=> "Hello, world"
msg = "Hello world"

=> "Hello world"

irb(main):008:0>  msg.insert 5, ","

=> "Hello, world"

以上方法可以在IRB中直接使用,你可以根据自己的需求选择适合的方法来替换字符串。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值