Scala 为什么这个简单的正则表达式不起作用

Scala 为什么这个简单的正则表达式不起作用,scala,Scala,这是scala书籍中的示例代码。 此对象有一个方法,可以删除给定字符串中的任何html标记。 但出于这个原因,它删除了整个字符串内容,而不仅仅是HTML标记。我可以知道为什么吗 object HtmlUtils { def removeMarkup(input: String) = { input.replaceAll("""</?\w[^>]*>""","") input.replaceAll("<.*>","") } } val a

这是scala书籍中的示例代码。 此对象有一个方法,可以删除给定字符串中的任何html标记。 但出于这个原因,它删除了整个字符串内容,而不仅仅是HTML标记。我可以知道为什么吗

object HtmlUtils {
 def removeMarkup(input: String) = {
    input.replaceAll("""</?\w[^>]*>""","")
    input.replaceAll("<.*>","")
   }
 }


val ahtmlText = "<html><body><h1>Introduction</h1></body></html>"

val anewhtmlText = HtmlUtils.removeMarkup(ahtmlText)

println(anewhtmlText)

println(s"Before removing html tags, the string was $ahtmlText and after rmoving html tags the string became $anewhtmlText")
对象HtmlUtils{
def removeMarkup(输入:字符串)={
input.replaceAll(“”]*>“”,“”)
input.replaceAll(“,”)
}
}
val ahtmlText=“简介”
val anewhtmlText=htmlitls.removeMarkup(ahtmlText)
println(anewhtmlText)
println(s“删除html标记之前,字符串为$ahtmlText,移动html标记之后,字符串为$ANEWHTMLEXT”)

您的第二个
replaceAll
不需要,并且将删除所有由于贪婪匹配而被
*
删除的内容。此外,如果需要,您的第一个
replaceAll
也可以通用化。以下修订的
removeMarkup
应该适合您:

object HtmlUtils {
  def removeMarkup(input: String) = {
    input.replaceAll("""</?[^>]*>""", "")
  }
}

scala> val ahtmlText = "<html><body><h1>Introduction</h1></body></html>"
ahtmlText: String = <html><body><h1>Introduction</h1></body></html>

scala> val anewhtmlText = HtmlUtils.removeMarkup(ahtmlText)
anewhtmlText: String = Introduction
对象HtmlUtils{
def removeMarkup(输入:字符串)={
input.replaceAll(“”]*>“”,“”)
}
}
scala>val ahtmlText=“简介”
ahtmlText:String=简介
scala>val anewhtmlText=htmlitls.removeMarkup(ahtmlText)
anewhtmlText:String=简介