简体   繁体   中英

Replace “OS agnostic” newlines

I have several different document formats coming in. I'd like to strip out all the newlines and replace them with a " " . How can I account for newlines other than "\\n" ?

Something like s.gsub("\\n", " ")

Most operating systems use \\n or \\r (or a combination) for newlines.

s.gsub(/[\\n\\r]+/, " ") should do the trick.

/[\\n\\r]+/ is known as a regular expression. It matches \\n , \\r and any combination of the two.

To make it your code more readable you could however use my gem .

You can install it this way:

gem install linebreak

You can use it this way:

require 'aef/linebreak/string_extension'

"Something\n".linebreak_encode(" ")
# => "Something "

Other examples:

"Something\n".linebreak_encode(:windows)
# => "Something\r\n"

"Something\r\n".linebreak_encode(:unix)
# => "Something\n"

It additionally comes with a commandline tool. Documentation can be found here .

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM