如何从java中的字符串中删除一些单词

时间:2011-05-31 10:14:43

标签: java android string replace

我在Android平台上工作,我使用字符串变量来填充html内容之后我想删除一些单词(具体 - 删除<head>..</head>标记之间的任何单词。任何解决方案?

3 个答案:

答案 0 :(得分: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

答案 1 :(得分: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());

答案 2 :(得分:0)

尝试:

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