Scala:从字符串中替换换行符、制表符和返回序列

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17581714/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-22 05:28:43  来源:igfitidea点击:

Scala: Replace newline, tab and return sequences from string

scalascalatra

提问by randombits

I have a string of HTML that I'm copy pasting into a String object that looks something like the following:

我有一个 HTML 字符串,我将其复制粘贴到一个类似于以下内容的 String 对象中:

val s = """<body>
   <p>This is a test</p>  <p>This is a test 2</p>
 </body"""

The problem here is, when I display this string as JSON within the context of a web browser, the output displays literal \nand \tcharacters to the tune of something like this:

这里的问题是,当我在 Web 浏览器的上下文中将此字符串显示为 JSON 时,输出会显示文字\n\t字符以进行如下调整:

"<body>\n <p>This is a test</p>\t <p>This is a test 2</p>\n</body>"

Is it possible to perhaps strip all of these escaped sequences from my strings output in Scala?

是否有可能从 Scala 的字符串输出中去除所有这些转义序列?

回答by Rex Kerr

You could just

你可以

s.filter(_ >= ' ')

to throw away all control characters.

扔掉所有控制字符。

If you want to omit extra whitespace at the start/end of lines also, you can instead

如果您还想在行的开头/结尾省略额外的空格,您可以改为

s.split('\n').map(_.trim.filter(_ >= ' ')).mkString