[英]java Regular expression matching html
解決方案:
String p="<pre>[\\\\w\\\\W]*</pre>";
我想匹配並捕獲<pre> </ pre>標記的包圍內容,嘗試了以下操作,但不起作用,怎么了?
String p="<pre>.*</pre>"; Matcher m=Pattern.compile(p,Pattern.MULTILINE|Pattern.CASE_INSENSITIVE).matcher(input); if(m.find()){ String g=m.group(0); System.out.println("g is "+g); }
您需要DOTALL標志,而不是MULTILINE。 MULTILINE改變^
和$
的行為,而DOTALL是允許的行為.
匹配行分隔符。 您可能也想使用勉強的量詞:
String p = "<pre>.*?</pre>";
實際上,正則表達式不是正確的工具。 使用解析器。 Jsoup是一個不錯的選擇。
Document document = Jsoup.parse(html);
for (Element element : document.getElementsByTag("pre")) {
System.out.println(element.text());
}
parse()
方法還可以采用URL
或File
。
我之所以推薦Jsoup的原因是,它是我嘗試過的所有HTML解析器中最不冗長的。 它不僅提供類似JavaScript的方法,返回實現Iterable
元素,而且還支持類似選擇器的jQuery ,這對我來說是一大好處。
String stringToSearch = "H1 FOUR H1 SCORE AND SEVEN YEARS AGO OUR FATHER...";
// the case-insensitive pattern we want to search for
Pattern p = Pattern.compile("H1", Pattern.CASE_INSENSITIVE);
Matcher m = p.matcher(stringToSearch);
// see if we found a match
int count = 0;
while (m.find())
count++;
System.out.println("H1 : "+count);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.