2013-08-21 76 views
3

Recentrly删除口音,我发现非常有用的方法StringUtils的图书馆是从字符串

StringUtils.stripAccents(String s) 

我发现它真的有用以消除任何特殊字符并将其转换为一些ASCII“等价物”,对于instace C = C等

现在我正在为德国客户谁真的需要做这样的事情,但只为非德语字符工作。任何变音都应该保持不变。我意识到在这种情况下,弦乐器不会有用。

有没有人有这方面的经验? 是否有任何有用的工具/库/类或正则表达式? 我试着写一些类,这是分析和更换等字符,但它可以建立这样的地图所有的语言非常困难......

任何建议appriciated ...

回答

1

我的直觉告诉我,最简单的方法是只列出允许的字符并去掉所有其他字符。这将是像

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}+", ""); 
    } 
} 

(我知道的模式不包含可能需要的所有字符,但添加任何缺失)

0

This可能围绕给你的工作。在这里您可以检测语言并仅获取特定文本。

编辑: 你可以有原始字符串作为输入,把语言检测到德国,然后将检测到德国的字符,并丢弃剩下的。

+0

它似乎有检测所使用的语言的功能。你能澄清这将如何帮助? – eis

+0

你可以有原始字符串作为输入,把语言检测到德国,然后将检测到德国的字符,并丢弃剩余 –

2

最好构建了一个自定义函数。它可以像下面这样。如果您想避免转换字符,则可以删除两个字符串(常量)之间的关系

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")); 
}