我想从我的 html 内容中删除一些特定的文本。我在 java 中使用 replaceAll 方法将内容替换为“”来实现这一点。
我的内容是
<html xmlns="http://www.w3.org/1999/xhtml" lang="fr-CA" xml:lang="fr-CA"> or
<html xmlns="http://www.w3.org/1999/xhtml" lang="en-AU" xml:lang="en-AU"> or
<html xmlns="http://www.w3.org/1999/xhtml" lang="en-GB" xml:lang="en-GB"> or
<html xmlns="http://www.w3.org/1999/xhtml" lang="en-IE" xml:lang="en-IE"> or
<html xmlns="http://www.w3.org/1999/xhtml" lang="es-PR" xml:lang="es-PR> or
<html xmlns="http://www.w3.org/1999/xhtml" lang="en-US" xml:lang="en-US">
我想删除 lang="-"
xml:lang="-"
如您所见,lang 和 xml:lang 的值是动态变化的。所以我想要一个可以检测这个特定字符串序列的正则表达式,然后我将使用 Java 中的 replaceAll(regex, string)
方法将其替换为“”。
最佳答案
这个答案是基于这样的假设
<html xmlns="http://www.w3.org/1999/xhtml" lang="fr-CA" xml:lang="fr-CA"> or <html xmlns="http://www.w3.org/1999/xhtml" lang="en-AU" xml:lang="en-AU"> or ...
意味着你有像
这样的 HTML 结构<html xmlns="http://www.w3.org/1999/xhtml" lang="fr-CA" xml:lang="fr-CA">
...
</html>
或
<html xmlns="http://www.w3.org/1999/xhtml" lang="en-AU" xml:lang="en-AU">
...
</html>
在这种情况下,不要使用正则表达式,而是使用像 Jsoup 这样的 HTML/XML 解析器。你的代码可能看起来像
String htmlText =
"<html xmlns=\"http://www.w3.org/1999/xhtml\" lang=\"fr-CA\" xml:lang=\"fr-CA\">" +
" <body>hello</body>" +
"</html>";
//use XML parser if you don't want Jsoup to change optimize your HTML code
Document doc = Jsoup.parse(htmlText,"",Parser.xmlParser());
Elements htmlTag = doc.select("html");
htmlTag.removeAttr("lang").removeAttr("xml:lang");//remove these attributes from selected tag
String replaced = doc.toString();
System.out.println(replaced);
关于java - 用动态内容中的另一个字符串替换子字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29941634/