54

Right now I'm doing a split on a string and assuming that the newline from the user is \r\n like so:

string.split(/\r\n/)

What I'd like to do is split on either \r\n or just \n.

So how what would the regex be to split on either of those?

8 Answers 8

79

Did you try /\r?\n/ ? The ? makes the \r optional.

Example usage: http://rubular.com/r/1ZuihD0YfF

3
  • This is the right solution to the wrong problem. You shouldn't be geting \rs in your text. Jul 4, 2011 at 7:58
  • 13
    @AndrewGrimm, why do you assume the user should never have \r's in his text?
    – Kirk Woll
    Aug 21, 2012 at 18:57
  • what if the lines are only \r?
    – Arnold Roa
    Jan 20, 2016 at 19:00
17

Ruby has the methods String#each_line and String#lines

returns an enum: http://www.ruby-doc.org/core-1.9.3/String.html#method-i-each_line

returns an array: http://www.ruby-doc.org/core-2.1.2/String.html#method-i-lines

I didn't test it against your scenario but I bet it will work better than manually choosing the newline chars.

2
  • This is what I was looking for. For some reason, it's keeping the \n\r, I had to use .map(&:squish) on the array. Nov 4, 2014 at 19:31
  • This solution is not applicable, as it does not consider different newline sequences: String#lines splits on the input record separator $/ by default (see), which is newline ("\n") by default (see). However, no need to consider different newline chars as Ruby does it already (see).
    – tanius
    May 25, 2020 at 19:37
15
# Split on \r\n or just \n
string.split( /\r?\n/ )

Although it doesn't help with this question (where you do need a regex), note that String#split does not require a regex argument. Your original code could also have been string.split( "\r\n" ).

6
\n is for unix 
\r is for mac 
\r\n is for windows format

To be safe for operating systems. I would do /\r?\n|\r\n?/

"1\r2\n3\r\n4\n\n5\r\r6\r\n\r\n7".split(/\r?\n|\r\n?/)
=> ["1", "2", "3", "4", "", "5", "", "6", "", "7"]
1
  • the most complete answer, don't understand why no up more upvotes. On mac file all other solution are not doing any split Sep 13, 2018 at 13:28
3

The alternation operator in Ruby Regexp is the same as in standard regular expressions: |

So, the obvious solution would be

/\r\n|\n/

which is the same as

/\r?\n/

i.e. an optional \r followed by a mandatory \n.

2
  • "The same as"? Not necessarily. Generally, it's good to avoid | in regular expressions when possible, as it makes them more inefficient.
    – NickAldwin
    Jul 1, 2011 at 17:24
  • 4
    @NickAldwin: I meant semantically. I'd think that any halfway decent compiler should be able to merge common prefixes and suffixes and turn the first form into the second one, no? After all, Regexp are not Turing-complete (well, Ruby 1.9's actually maybe are), so, unlike normal programming languages, not every optimization attempt automatically involves solving the Halting Problem. Jul 1, 2011 at 18:04
2

Are you reading from a file, or from standard in?

If you're reading from a file, and the file is in text mode, rather than binary mode, or you're reading from standard in, you won't have to deal with \r\n - it'll just look like \n.

C:\Documents and Settings\username>irb
irb(main):001:0> gets
foo
=> "foo\n"
1
1

Perhaps do a split on only '\n' and remove the '\r' if it exists?

0

Another option is to use String#chomp, which also handles newlines intelligently by itself.

You can accomplish what you are after with something like:

lines = string.lines.map(&:chomp)

Or if you are dealing with something large enough that memory use is a concern:

<string|io>.each_line do |line|
  line.chomp!
  #  do work..
end

Performance isn't always the most important thing when solving this kind of problem, but it is worth noting the chomp solution is also a bit faster than using a regex.

On my machine (i7, ruby 2.1.9):

Warming up --------------------------------------
           map/chomp    14.715k i/100ms
  split custom regex    12.383k i/100ms
Calculating -------------------------------------
           map/chomp    158.590k (± 4.4%) i/s -    794.610k in   5.020908s
  split custom regex    128.722k (± 5.1%) i/s -    643.916k in   5.016150s

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.