Split on different newlines

前端 未结 8 1089
自闭症患者
自闭症患者 2021-02-01 12:57

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/)
<         


        
相关标签:
8条回答
  • 2021-02-01 13:25

    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.

    0 讨论(0)
  • 2021-02-01 13:25

    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.

    0 讨论(0)
提交回复
热议问题