New line character in Scala

2019-02-11 14:47发布

Is there a shorthand for a new line character in Scala? In Java (on Windows) I usually just use "\n", but that doesn't seem to work in Scala - specifically

val s = """abcd
efg"""
val s2 = s.replace("\n", "")
println(s2)

outputs

abcd
efg

in Eclipse,

efgd

(sic) from the command line, and

abcdefg

from the REPL (GREAT SUCCESS!)

String.format("%n") works, but is there anything shorter?

标签: scala newline
6条回答
冷血范
2楼-- · 2019-02-11 14:56

Use \r\n instead

Before:

before

After:

after

查看更多
做个烂人
3楼-- · 2019-02-11 15:03

If you're sure the file's line separator in the one, used in this OS, you should do the following:

s.replaceAll(System.lineSeparator, "")

Elsewhere your regex should detect the following newline sequences: "\n" (Linux), "\r" (Mac), "\r\n" (Windows):

s.replaceAll("(\r\n)|\r|\n", "")

The second one is shorter and, I think, is more correct.

查看更多
一纸荒年 Trace。
4楼-- · 2019-02-11 15:05
var s = """abcd
efg""".stripMargin.replaceAll("[\n\r]","")
查看更多
太酷不给撩
5楼-- · 2019-02-11 15:12

Your Eclipse making the newline marker the standard Windows \r\n, so you've got "abcd\r\nefg". The regex is turning it into "abcd\refg" and Eclipse console is treaing the \r slightly differently from how the windows shell does. The REPL is just using \n as the new line marker so it works as expected.

Solution 1: change Eclipse to just use \n newlines.

Solution 2: don't use triple quoted strings when you need to control newlines, use single quotes and explicit \n characters.

Solution 3: use a more sophisticated regex to replace \r\n, \n, or \r

查看更多
在下西门庆
6楼-- · 2019-02-11 15:12

A platform-specific line separator is returned by

sys.props("line.separator")

This will give you either "\n" or "\r\n", depending on your platform. You can wrap that in a val as terse as you please, but of course you can't embed it in a string literal.

If you're reading text that's not following the rules for your platform, this obviously won't help.

References:

查看更多
疯言疯语
7楼-- · 2019-02-11 15:12

Try this interesting construction :)

import scala.compat.Platform.EOL
println("aaa"+EOL+"bbb")
查看更多
登录 后发表回答