0

我正在尝试使用 foldLeft 将用户名替换为隐藏值并将其打印出来

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)
}

但是它仍在打印出用户名,并且我收到错误消息message.replaceAll,说:

将“$”锚定在意外位置

4

2 回答 2

2

无需使用正则表达式。


  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
于 2021-09-06T14:36:02.693 回答
1

没有必要使用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>")
于 2021-09-06T18:33:20.277 回答