在scala中删除字符串中所有与模式匹配的子字符串

时间:2019-04-30 04:24:08

标签: string scala substring

我正在尝试使用Scala删除字符串中所有以“ [tpl]”开头并以“ [/ tpl]”结尾的子字符串。同一字符串中可能存在这些子字符串的多个实例。

示例字符串:“今天是星期三。[tpl]我们去钓鱼。[/ tpl]然后我们去公园。[tpl]但是天气很冷。[/ tpl]没关系。”

预期输出:“今天是星期三。那我们去公园吧。没关系。”

var noTPL = ListBuffer[Char]()
var foundTPL = false

input.foreach(char => {
  if (input.indexOf(char) < input.length() - 5 && input.substring(input.indexOf(char), input.indexOf(char) + 5) == "[tpl]") {
    foundTPL = true
  }
  if (input.indexOf(char) < input.length() - 6 && input.substring(input.indexOf(char), input.indexOf(char) + 6) == "[/tpl]") {
    foundTPL = false
    println("FOUND [/tpl]")
  }
  if (!foundTPL) {
    noTPL += char
  }
})`

此代码找到“ [tpl]”,但从未找到“ [/ tpl]”

2 个答案:

答案 0 :(得分:1)

正如Harald在他的评论中建议的那样,您可以使用正则表达式。

假设您输入的是:

val input = "Today is Wednesday.[tpl] Let's go fishing.[/tpl]."

您可以使用以下方法获取所需的字符串:

val noTPL = input.replaceAll("\\[tpl\\]|\\[/tpl\\].*?", "")

出于完整性考虑,请检查replaceAll方法here的文档。

答案 1 :(得分:1)

您可以使用正则表达式,但是如果您想使用“ by steam”版本(我认为可能更清楚),请尝试一下。请注意,使用indexOfSlicepatch可以简化事情。

  val input = "Today is Wednesday.[tpl] Let's go fishing.[/tpl] Then let's go to the park.[tpl] But it is cold out.[/tpl] Nevermind."

  def stripTags(input: String): String = {
    val start = input.indexOfSlice("[tpl]")
    val end = input.indexOfSlice("[/tpl]")

    if (start != -1 && end != -1) {
      // we have a pair
      val actualEnd = end + "[/tpl]".length

      stripTags(input.patch(start, "", actualEnd - start))
    } else
      input
  }

 stripTags(input) // "Today is Wednesday. Then let's go to the park. Nevermind."
相关问题