替换字符串中的Unicode字符

问题描述

我需要将变音符号(例如ä,ó等)替换为其“基本”字符。对于大多数字符,此解决方案有效:

StringUtils.stripAccents(tmpStr);

但是它错过了四个字符:æ,œ,ø和ß。

我在Is there a way to get rid of accents and convert a whole string to regular letters?处查看了此解决方案。我认为第一个解决方案可以用,但是没有用。

如何将这些字符替换为其“基本”字符(例如,将æ替换为a)。

解决方法

源代码显示(https://commons.apache.org/proper/commons-lang/apidocs/src-html/org/apache/commons/lang3/StringUtils.html),

public static String stripAccents(final String input) {
    if (input == null) {
        return null;
    }        final StringBuilder decomposed = new StringBuilder(Normalizer.normalize(input,Normalizer.Form.NFD));        convertRemainingAccentCharacters(decomposed);        

    // Note that this doesn't correctly remove ligatures...   
 
    return STRIP_ACCENTS_PATTERN.matcher(decomposed).replaceAll(EMPTY);    
}

有一条评论说, // Note that this doesn't correctly remove ligatures...

因此,您可能需要手动替换那些实例。 像

    String string = Normalizer.normalize("Tĥïŝ ĩš â fůňķŷ ß æ œ ø Šťŕĭńġ",Normalizer.Form.NFKD);
    string = string.replaceAll("\\p{M}","");

    string = string.replace("ß","s");
    string = string.replace("ø","o");
    string = string.replace("œ","o");
    string = string.replace("æ","a");

变音字符到ASCII字符映射 https://docs.oracle.com/cd/E29584_01/webhelp/mdex_basicDev/src/rbdv_chars_mapping.html

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...