2017-04-01 43 views
0

这是一本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") 

回答

0

你的第二个不需要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 
相关问题