Split on different newlines

2019-03-10 12:55发布

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条回答
时光不老,我们不散
2楼-- · 2019-03-10 13:26
\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"]
查看更多
Summer. ? 凉城
3楼-- · 2019-03-10 13:33

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

查看更多
登录 后发表回答