This article explores different ways to split a string on newline in Kotlin.

Different operating systems uses different line terminator wrt each other. For example, Windows uses a carriage-return and line-feed character (\r\n) as a line terminator. Mac uses a carriage-return character (represented as \r) and Unix uses a line-feed character (represented as \n) to mark the end of a line.

 
The split​() function is often used to split a string around matches of a regular expression. To split a string on newlines, we can use the regular expression \r?\n|\r which matches with all different line terminator i.e., \r\n, \r, and \n.

Download Code

 
To skip empty lines, we can change the regular expression to [\r\n]+.

Download Code

 
To match with any Unicode linebreak sequence, we can use the linebreak matcher \R.

Download Code

That’s all about splitting a string on newline in Kotlin.