开发者

how to remove some words from a string in java

开发者 https://www.devze.com 2023-03-09 17:11 出处:网络
im working on android platform,I use a string variable to fillthe html content after that i want to delete some words(Specifically- delete whatever words are there in between &l开发者_如何学Got;head&g

im working on android platform,I use a string variable to fill the html content after that i want to delete some words(Specifically- delete whatever words are there in between &l开发者_如何学Got;head>..</head> tag. Any solution?


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

Explanation:

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


Another solution :)

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());


Try:

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

精彩评论

暂无评论...
验证码 换一张
取 消