2011-05-31 121 views

回答

4
String newHtml = oldHtml.replaceFirst("(?s)(<head>)(.*?)(</head>)","$1$3"); 

說明:

oldHtml.replaceFirst(" // we want to match only one occurrance 
(?s)     // we need to turn Pattern.DOTALL mode on 
         // (. matches everything, including line breaks) 
(<head>)    // match the start tag and store it in group $1 
(.*?)     // put contents in group $2, .*? will match non-greedy, 
         // i.e. select the shortest possible match 
(</head>)    // match the end tag and store it in group $3 
","$1$3");    // replace with contents of group $1 and $3 
+0

謝謝這是我所期望的... – vnshetty 2011-05-31 10:45:38

0

嘗試:?

String input = "...<head>..</head>..."; 
String result = input.replaceAll("(?si)(.*<head>).*(</head>.*)","$1$2"); 
+0

將無法​​正常工作 – 2011-05-31 10:20:52

+1

真,感謝您的評論。 – morja 2011-05-31 10:22:22

3

另一種解決方案:)如果內容包含換行符(這幾乎是肯定的情況下)

String s = "Start page <head> test </head>End Page"; 
StringBuilder builder = new StringBuilder(s); 
builder.delete(s.indexOf("<head>") + 6, s.indexOf("</head>")); 

System.out.println(builder.toString());