替换标题HTML标记中特定属性内的德语元音变音符



我有一个很大的HTML文件,里面有很多行,比如

<h1 id="anwendungsfälle-und--funktionen">Anwendungsfälle und -funktionen</h1> 
<h1 id="öl">Öl</h1>

我需要替换所有元音变音符字符(ü,ö,ä(,但仅替换<>之间的字符方括号(因此仅适用于标头id,不适用于其他地方。

<h1 id="anwendungsfaelle-und--funktionen">Anwendungsfälle und -funktionen</h1> 
<h1 id="oel">Öl</h1>

Id可以包含数字、单字符和双字符。我已经没有办法构建一个Java正则表达式来匹配这些id了。

我试过类似的东西

(<h)ds(id=")[A-Za-z0-9]*([-]{1}[A-Za-z0-9]*)*(">)

但这不起作用(我知道这不是Java regex,只是一个例子(。

您可以使用JSoup:

Document doc = Jsoup.parse(html); // Init the DOM structure
Elements hs = doc.select("*[id]");   // Find all tags with `id` attribute
for(int i = 0; i < hs.size(); i++){  // Iterate through the tags 
Element h = hs.get(i);           // Get the current element
if (h.tagName().matches("h\d+")) { // If its tag is a heading tag
String new_val = h.attr("id").replace("ä", "ae").replace("ö", "oe").replace("ü", "ue");
h.attr("id",new_val);  // Replace the id attribute with a new one
}
}
System.out.println(doc.toString());

或者regex:

Map<String, String> dictionary = new HashMap<String, String>();
dictionary.put("ä", "ae");
dictionary.put("ö", "oe");
dictionary.put("ü", "ue");
String s = "<h1 id="anwendungsfälle-und--funktionen">Anwendungsfälle und -funktionen</h1> n<h1 id="öl">Öl</h1>";
StringBuffer result = new StringBuffer();
Matcher m = Pattern.compile("(\G(?!^)|<h\d+\s+id=")([^"]*?)([üöä])").matcher(s);
while (m.find()) {
m.appendReplacement(result, m.group(1) + m.group(2) + dictionary.get(m.group(3)));
}
m.appendTail(result);
System.out.println(result.toString());
// => <h1 id="anwendungsfaelle-und--funktionen">Anwendungsfälle und -funktionen</h1> 
// <h1 id="oel">Öl</h1>

查看Java演示

Regex

(G(?!^)|<hd+s+id=")([^"]*?)([üöä])

请参阅在线演示。

  • (G(?!^)|<hd+s+id=")-组1:上一次匹配的结束(G(?!^)(或(|(<h,1+位,1+空格,id="(请参阅<hd+s+id="(
  • ([^"]*?)-第2组:任何0+个字符,尽可能少,"除外
  • ([üöä])-组3:集合中定义的任何单个字符

要在<...>内部匹配,可以使用一个更简单的正则表达式:(G(?!^)|<)([^<>]*?)([üöä])

与针对标记语言使用的所有正则表达式一样,可能会出现边缘情况(例如,当><未序列化或有多个不同顺序的属性时(,但这种情况不起作用。只有当您确定要使用的数据格式时,才能使用它

您的正则表达式需要如下所示:

(?<="\Wid\=\"[^"]*)(ä)(?=[^"]\"") // -> ae
(?<="\Wid\=\"[^"]*)(ö)(?=[^"]\"") // -> oe
(?<="\Wid\=\"[^"]*)(ü)(?=[^"]\"") // -> ...
(?<="\Wid\=\"[^"]*)(Ä)(?=[^"]\"")
(?<="\Wid\=\"[^"]*)(Ö)(?=[^"]\"")
(?<="\Wid\=\"[^"]*)(Ü)(?=[^"]\"")
(?<="\Wid\=\"[^"]*)(ß)(?=[^"]\"") // -> ss

请意识到,这并不完美。可能会出现边缘情况,在这种情况下会失败。

最新更新