1

I used chomp to remove multiple "\n" from a string, but it only removes one. How can I remove multiple "\n" characters from a string?

My string looks like:

"Ttyyuhhhjhhhh\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n"
1
  • I see you are rather new to Stackoverflow (incidentally, so am I). Remember that after asking a question, once/if you receive an answer that truly answers your question, is a good idea to approve it. @gargvipan Commented Nov 17, 2012 at 5:10

4 Answers 4

8

The method strip will take care of removing all leading and trailing white spaces for you.

If you only want to remove the \n from the end of the string you can use a regexp such as:

string.gsub!(/(\n*)$/, '')

or rstrip!

string.rstrip!
Sign up to request clarification or add additional context in comments.

7 Comments

Well, "...leading and trailing white space...".
You are right, I always thought of white space as referring to only horizontal space, but I see now that vertical is also included in the definition. Thanks. Edited.
(\n*) is needlessly complex. There is no need to group \n, nor do you care about the case where there is no new-line so use \n by itself: sub(/\n+$/, '') is all that's needed.
@theTinMan IMO is the whole use of regular expression needlessly complex, why not to use *strip methods to actually strip the string?
Both ways are presented in this answer, regular expressions and strip.
|
8

As you need to strip from the end of your string, use rstrip

str = "Ttyyuhhhjhhhh\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n"
str.rstrip()

Comments

0

If you really just want to remove newlines, and not other whitespace, strip and rstrip (which remove all whitespace) are not the answer. The regex /\n+\Z/ will match any number of newlines at the end of a string:

str1 = "text \t\n\n\n"
# => "text \t\n\n\n"
str1.sub(/\n+\Z/, '')
# => "text \t"

Note that this works (and without the multiline regexp modifier /m) on multi-line strings as well, leaving newlines in the middle of the string intact:

str2 = str1 + str1 + str1
# => "text \t\n\n\ntext \t\n\n\ntext \t\n\n\n"
str2.sub(/\n+\Z/, '')
# => "text \t\n\n\ntext \t\n\n\ntext \t"

Comments

-2
"Ttyyuhhhjhhhh\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n".gsub(/\n$/,'')

1 Comment

The regex is wrong. /$\n/ would find new-lines after the current line, not new-lines at the end of the current line. Instead, you need /\n$/.

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.