2017-04-01 38 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 
相關問題