Scala: Replace newline, tab and return sequences from string

和自甴很熟 提交于 2019-12-09 07:54:10

问题


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"""

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>"

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


回答1:


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


来源:https://stackoverflow.com/questions/17581714/scala-replace-newline-tab-and-return-sequences-from-string

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!