I have a string
Java \n\n c# \n\n c/c++
i need to replace it becomes
Java \n c# \n c/c++
use regular expression in Ruby String
Thanks
Use squeeze function of String class
[18] pry(main)> "Java \n\n c# \n\n c/c++".squeeze("\n")
=> "Java \n c# \n c/c++"
However, it returns a new string where runs of the same character that occur in this set are replaced by a single character, So
[18] pry(main)> "Java \n\n\n\n\n c# \n\n\n\n\n c/c++".squeeze("\n")
=> "Java \n c# \n c/c++"
You probably want to eliminate triple and so forth occurencies as well. In such a case the best option is to use the match counter:
# ⇓⇓⇓⇓
'Java \n\n c# \n\n c/c++'.gsub /\\n{1,}/, '\n'
In this particular case, “one or more” has s syntactic sugar for it:
# ⇓
'Java \n\n c# \n\n c/c++'.gsub /\\n+/, '\n'
If you are using Ruby2, there is \R match to match any combination of \r and \n.
To eliminate exactly two occurencies, one might use:
# ⇓⇓⇓
'Java \n\n c# \n\n c/c++'.gsub /\\n{2}/, '\n'
And, finally, there is a function to remove multiple occurencies of \n from the string using named matches and backreferences:
def singlify s
s.gsub /(?<sym>\\n)\g<sym>+/, '\k<sym>'
end
singlify 'Java \n\n c# \n\n c/c++'
# Java \n c# \n c/c++'
'Java \n\n c# \n\n c/c++'.gsub! /\\n\\n/, '\n'
gsub("\n\n", "\n") is much cleaner