从String中删除重音符号

我终于在StringUtils库中找到了非常有用的方法

StringUtils.stripAccents(String s) 

我发现删除任何特殊字符并将其转换为某些ASCII“等效”非常有用,因为instaceç= c等。

现在我正在为一个真正需要做这样的事情的德国客户工作,但仅限于非德国人。 任何变音都应保持不变。 我意识到strinAccents在这种情况下不会有用。

有没有人对这些东西有一些经验? 是否有任何有用的工具/库/类或正则表达式? 我试着编写一些解析和替换这些字符的类,但是为所有语言构建这样的地图可能非常困难……

任何建议appriciated …

最好建一个自定义function。 它可能如下所示。 如果要避免转换字符,可以删除两个字符串(常量)之间的关系

 private static final String UNICODE = "ÀàÈèÌìÒòÙùÁáÉéÍíÓóÚúÝýÂâÊêÎîÔôÛûŶŷÃãÕõÑñÄäËëÏïÖöÜüŸÿÅåÇçŐőŰű"; private static final String PLAIN_ASCII = "AaEeIiOoUuAaEeIiOoUuYyAaEeIiOoUuYyAaOoNnAaEeIiOoUuYyAaCcOoUu"; public static String toAsciiString(String str) { if (str == null) { return null; } StringBuilder sb = new StringBuilder(); for (int index = 0; index < str.length(); index++) { char c = str.charAt(index); int pos = UNICODE.indexOf(c); if (pos > -1) sb.append(PLAIN_ASCII.charAt(pos)); else { sb.append(c); } } return sb.toString(); } public static void main(String[] args) { System.out.println(toAsciiString("Höchstalemannisch")); } 

我的直觉告诉我,最简单的方法就是列出允许的字符并从其他所有内容中删除重音。 这就像是

 import java.util.regex.*; import java.text.*; public class Replacement { private static String patternContainingAllValidGermanCharacters = "a-zA-Z0-9äÄöÖéÉüÜß"; public static void main(String args[]) { String from = "aoeåöäìé"; String result = stripAccentsFromNonGermanCharacters(from); System.out.println("Result: " + result); } public static String stripAccentsFromNonGermanCharacters( String from) { Pattern nonGermanCharactersPattern = Pattern.compile( "([^" + patternContainingAllValidGermanCharacters + "])"); return stripAccentsFromCharactersMatching( from, nonGermanCharactersPattern); } public static String stripAccentsFromCharactersMatching( String target, Pattern myPattern) { StringBuffer myStringBuffer = new StringBuffer(); Matcher myMatcher = myPattern.matcher(target); while (myMatcher.find()) { myMatcher.appendReplacement(myStringBuffer, stripAccents(myMatcher.group(1))); } myMatcher.appendTail(myStringBuffer); return myStringBuffer.toString(); } // pretty much the same thing as StringUtils.stripAccents(String s) // used here so I can demonstrate the code without StringUtils dependency public static String stripAccents(String text) { return Normalizer.normalize(text, Normalizer.Form.NFD) .replaceAll("\\p{InCombiningDiacriticalMarks}+", ""); } } 

(我意识到模式可能不包含所需的所有字符,但添加了缺少的内容)

这可能会给你一个解决方法。 在这里,您可以检测语言并仅获取特定文本。

编辑:您可以将原始字符串作为输入,将语言检测放到德语,然后它将检测德语字符并将丢弃剩余的字符。