How to use a foldLeft using a regex

84 Views Asked by At

I am trying to use a foldLeft to replace user names with a hidden value and print them out

private def removeNamesFromErrorMessage(errorMessage: String): Unit = {

    val userNames = List("mary", "john")
    val errorMessage = "users mary and john have not paid their fee "
    
    val newError = userNames.foldLeft(errorMessage)((message, name) => message.replaceAll(s"${name}:\\s?[a-zA-Z0-9-_.]+", s"${name}: <HIDDEN USER>"))
    println(newError)
}

However it is still printing out the user names and I am getting an error on message.replaceAll, saying:

Anchor '$' in unexpected position

2

There are 2 best solutions below

0
Alec On

There is no need to use regex.


  val userNames = List("mary", "john")
  val errorMessage = "users mary and john have not paid their fee"

  val newError = userNames.foldLeft(errorMessage)((message, name) => message.replaceAll(name,"<HIDDEN USER>"))
  println(newError)

users <HIDDEN USER> and <HIDDEN USER> have not paid their fee
0
jwvh On

There is no need to use foldLeft().

val userNames    = List("mary", "john")
val errorMessage = "users mary and john have not paid their fee"
val newError = userNames.mkString("|").r
                        .replaceAllIn(errorMessage, "<HIDDEN USER>")