我有一个动态生成的字符串,其中可以包含任意数量的“:”示例。
example1: "test string:: this is test string"
example2: "test string:::: this is test string"
我想将此类字符串转换为以下
result string1: "test string: this is test string"
result string2: "test string: this is test string"
请帮忙
答案 0 :(得分:5)
"test string:::: this is test string".squeeze(':')
#=> "test string: this is test string"
"test string:::: this is:: test string".squeeze(':')
#=> "test string: this is: test string"
另一种方法是使用String#gsub(或String#sub如果字符串中最多有一次冒号运行。)
"test string:::: this is:: test string".gsub(/:+/, ':')
#=> "test string: this is: test string"