I have a String s
, which in general (but see below) contains several \n
, hence can be regarded as multiline string. I want to get the first line (excluding the terminating newline); but if there is no newline at all, the whole string should be returned. Example:
"abc\ndef" -> "abc"
"\ndef" -> ""
"xyz" -> "xyz"
My first attempt was
s[/.*(?=\n)/]
but this returns nil if there is no newline in s (because the lookahead expression does not match). I then considered
s[0,s.index("\n")||s.length]
This does work, but I need to mention the variable (s
) three times and find this aesthetically unpleasant. Has someone an idea of how to write a concise expression which would work here?
UPDATE: I don't want to scan the whole string (which in general is fairly large). I need it parsed only up the the first newline character.