Как удалить некоторые слова из строки в Java - PullRequest
4 голосов
/ 31 мая 2011

я работаю на платформе Android, я использую строковую переменную для заполнения содержимого html, после чего я хочу удалить некоторые слова (в частности, удалить любые слова между тегом <head>..</head>. Любое решение?

Ответы [ 3 ]

4 голосов
/ 31 мая 2011
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
3 голосов
/ 31 мая 2011

Другое решение:)

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());
0 голосов
/ 31 мая 2011

Попробуйте:

String input = "...<head>..</head>...";
String result = input.replaceAll("(?si)(.*<head>).*(</head>.*)","$1$2");
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...