0

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

3 Answers 3

4

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++"
Sign up to request clarification or add additional context in comments.

1 Comment

Thoese work well for me 'Java \n\n c# \n\n c/c++'.squeeze!("\n") 'Java \n\n c# \n\n c/c++'.gsub!(/\n{1,}/) Thanks all,
1

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++'

1 Comment

Thoese work well for me 'Java \n\n c# \n\n c/c++'.squeeze!("\n") 'Java \n\n c# \n\n c/c++'.gsub!(/\n{1,}/) Thanks all,
0
'Java \n\n c# \n\n c/c++'.gsub! /\\n\\n/, '\n'

1 Comment

gsub("\n\n", "\n") is much cleaner

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.