2

Is there a way to remove special characters(\n, \b, \t, \f, \r) from a multi line string in Scala?

for a normal string

val someText = "some\nText\t"
someText.filter(_ >= ' ')       // returns "someText"

How do I achieve the same, in multi line string

val multLineStr = """some\nText\t"""
someText.filter(_ >= ' ')       // returns "some\nText\t"

I tried using regular expressions, couldn't remove the characters from the string.

val regex = new Regex("\\s")
regex.replaceAllIn(multLineStr, "")   // returns "some\nText\t"
SCouto
  • 6,742
  • 4
  • 29
  • 40
chqdrian
  • 305
  • 3
  • 11
  • 3
    `"""\n"""` is a combination of two chars, not a newline. Use `val regex = """\\[tn]""".r` – Wiktor Stribiżew Feb 03 '20 at 11:51
  • 1
    This works: `println(">some\nText\t – diginoise Feb 03 '20 at 12:05
  • 2
    The triple-quoted strings are "multiline" which means that they understand the rendered new line. In other words, for every rendered new line, a `\n` character is automatically inserted. And special characters are not treated as special anymore. – sarveshseri Feb 03 '20 at 12:24
  • 1
    @diginoise, I wanted to replace "special chars" in triple quoted strings, although it's good to know another method to replace special chars in strings, thanks – chqdrian Feb 03 '20 at 12:30
  • So, you are not after *removing* anything, but *defining* inside a string literal? – Wiktor Stribiżew Feb 03 '20 at 12:32
  • I was after *removing* spec chars from the string, If you had *answered* my question, I would have accepted your solution @Wiktor Stribtizew. – chqdrian Feb 03 '20 at 16:10

2 Answers2

2

It seems like you need add interpolation to this string:

val multLineStr = """some\nText\t"""
println(multLineStr.toList)
println(multLineStr.filter(_ >= ' '))

will print out:

List(s, o, m, e, \, n, T, e, x, t, \, t)
some\nText\t

and same with s interpolation before the multi-line string

val multLineStr = s"""some\nText\t"""
println(multLineStr.toList)
println(multLineStr.filter(_ >= ' '))

will give your desired result:

List(s, o, m, e, 
, T, e, x, t,   )
someText
Ivan Kurchenko
  • 3,748
  • 1
  • 9
  • 27
1

As a side node, there exists StringContext.processEscapes method which

  /** Expands standard Scala escape sequences in a string.
   *  Escape sequences are:
   *   control: `\b`, `\t`, `\n`, `\f`, `\r`
   *   escape:  `\\`, `\"`, `\'`
   *
   *  @param  str  A string that may contain escape sequences
   *  @return The string with all escape sequences expanded.
   */
  def processEscapes(str: String): String

hence

assert(StringContext.processEscapes("""some\nText\t""") == "some\nText\t")

StringContext.processEscapes("""some\nText\t""").filter(_ >= ' ')
// res1: String = someText
Mario Galic
  • 41,266
  • 6
  • 39
  • 76