Scala:替换字符串中的换行符,制表符和返回序列 [英] Scala: Replace newline, tab and return sequences from string

查看:853
本文介绍了Scala:替换字符串中的换行符,制表符和返回序列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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

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

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

是否有可能从我在Scala中输出的字符串中剥离所有这些转义序列?

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

推荐答案

您可以

s.filter(_ >= ' ')

丢弃所有控制字符.

如果您还想在行首/末尾省略多余的空格,可以改为

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

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

这篇关于Scala:替换字符串中的换行符,制表符和返回序列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆