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中直接使用,你可以根据自己的需求选择适合的方法来替换字符串。

猜你喜欢

转载自blog.csdn.net/Toml_/article/details/131448604