用ruby中的单个字符替换字符串中的多个相同字符
我有一个动态生成的字符串,在它们之间可以有任意数量的“:”例如用ruby中的单个字符替换字符串中的多个相同字符,ruby,Ruby,我有一个动态生成的字符串,在它们之间可以有任意数量的“:”例如 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" 请帮助
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"
请帮助使用
另一种方法是使用(或者如果字符串中最多有一行冒号)
使用
另一种方法是使用(或者如果字符串中最多有一行冒号)
您应该删除Rails标记,因为这是一个纯粹的Ruby问题。读者通过标签过滤问题。Rails标签可能会吸引那些只对Rails问题感兴趣的读者,浪费他们的时间。这也可能导致读者对纯Ruby问题不感兴趣,因为他们已经过滤掉了Rails问题。(我看到你删除了Rails标签,但我会留下这个评论,因为标签被滥用了很多。)我看到你刚刚接受了我的答案。恐怕我还有别的抱怨!:-)当提问者很快打勾时,我经常对他们发牢骚,通常只有一个答案被贴出来。我不能很好地说这一次没关系,因为这是我选择的答案。Rapido选择可能会阻碍其他答案,在我看来,这些答案对那些仍在准备答案的人来说是不礼貌的,并且可能会导致错误答案不受质疑。没有匆忙,所以请考虑在未来等待至少几个小时(和/或暂时删除目前的检查标记)。当然,这取决于您。您应该删除Rails标记,因为这是一个纯粹的Ruby问题。读者通过标签过滤问题。Rails标签可能会吸引那些只对Rails问题感兴趣的读者,浪费他们的时间。这也可能导致读者对纯Ruby问题不感兴趣,因为他们已经过滤掉了Rails问题。(我看到你删除了Rails标签,但我会留下这个评论,因为标签被滥用了很多。)我看到你刚刚接受了我的答案。恐怕我还有别的抱怨!:-)当提问者很快打勾时,我经常对他们发牢骚,通常只有一个答案被贴出来。我不能很好地说这一次没关系,因为这是我选择的答案。Rapido选择可能会阻碍其他答案,在我看来,这些答案对那些仍在准备答案的人来说是不礼貌的,并且可能会导致错误答案不受质疑。没有匆忙,所以请考虑在未来等待至少几个小时(和/或暂时删除目前的检查标记)。当然,由你决定。
"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"
"test string:::: this is:: test string".gsub(/:+/, ':')
#=> "test string: this is: test string"