簡體   English   中英

如何從 java 中的字符串中刪除一些單詞

[英]how to remove some words from a string in java

我在 android 平台上工作,我使用字符串變量來填充 html 內容,之后我想刪除一些單詞(具體來說 - 刪除<head>..</head>標簽之間的任何單詞。有什么解決方案嗎?

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

另一個解決方案:)

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

嘗試:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM