I have a dynamically generated string which can have any number of ":" in-between them example.
example1: "test string:: this is test string"
example2: "test string:::: this is test string"
I want to convert such string into following
result string1: "test string: this is test string"
result string2: "test string: this is test string"
Please help
Use String#squeeze .
"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"
Another way is to use String#gsub (or String#sub if there is at most one run of colons in the string).
"test string:::: this is:: test string".gsub(/:+/, ':')
#=> "test string: this is: test string"
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.