5

我需要经常调用这个函数。基本上,它将所有重音字符替换为其非重音等价物,将空格更改为“_”,转换为小写,并去除其余的外来代码,因此可以安全地用作文件名/url路径/等。问题是,如您所见,从性能的角度来看,它看起来很糟糕。有人能想到更清洁、更快的替代方案吗?

public static String makeValidPathName(String rawString) {
    if (rawString==null) return null;
    rawString = rawString.replaceAll("[ÁÀÂÄáàäaàáâãäå]","a");
    rawString = rawString.replaceAll("æ","ae");
    rawString = rawString.replaceAll("çÇ","c");
    rawString = rawString.replaceAll("[ÈÉÊËèéêë]","e");
    rawString = rawString.replaceAll("[ìíîïÍÌÎÏ]","i");
    rawString = rawString.replaceAll("ñÑ","n");                            
    rawString = rawString.replaceAll("[ÓÓÖÔòóôõö]","o");
    rawString = rawString.replaceAll("œ","oe");
    rawString = rawString.replaceAll("[ÙÚÛÜùúûü]", "u");
    rawString = rawString.replaceAll("[ýÿ]","y");
    rawString= rawString.replaceAll("[^a-z A-Z 0-9 \\_ \\+]","");
    rawString = rawString.replaceAll(" ","_");
    return rawString.toLowerCase();
}

- - 编辑

好的,伙计们......我对所有 4 个案例进行了性能测试:

  • 案例1)这里发布的原始例程。
  • 案例2)@WChargin 建议的改进
  • 案例 3)@devconsole 建议的查找表以及我对 SparseArray 的优化
  • 案例 4)@Erik Pragt 建议的 Normalizer 方法

而且......获胜者是...... TADAAAA ......

D/REPLACEMENT_TEST(18563): *** Running Tests (1000 iterations)
D/REPLACEMENT_TEST(18563): Original REGEX  : 13533 ms
D/REPLACEMENT_TEST(18563): Compiled REGEX  : 12563 ms
D/REPLACEMENT_TEST(18563): Character LUT   : 1840 ms
D/REPLACEMENT_TEST(18563): Java NORMALIZER : 2416 ms
  • 有趣的是,模式编译优化并没有太大帮助。
  • 我发现我对 REGEXES 速度的假设也是完全错误的,而 devconsole 在他对 Normalizer 优于正则表达式的有根据的猜测中是正确的。
  • 令人惊讶的是 REGEXES 的速度有多慢。一个数量级的差异真的让我感到惊讶。我会尽量避免在 Java 上使用它们。
  • 查找表是短边距最快的选项。我会坚持使用这个解决方案,因为有了 Normalizer 之一,我仍然需要手动替换一些字符(空格变成“_”),然后转换为小写。

测试是在三星 Galaxy Tab v1 10.1 中完成的。

请在附件中找到测试用例的源代码。

public class Misc { 

    /* Test 2 (@WCChargin's Regex compilation) initialization */

static Map<Pattern, String> patterns = new HashMap<Pattern, String>();

static {
        patterns.put(Pattern.compile("[ÁÀÂÄáàäaàáâãäå]") ,"a");
        patterns.put(Pattern.compile("æ"),"ae");
        patterns.put(Pattern.compile("çÇ"),"c");
        patterns.put(Pattern.compile("[ÈÉÊËèéêë]"),"e");
        patterns.put(Pattern.compile("[ìíîïÍÌÎÏ]"),"i");
        patterns.put(Pattern.compile("ñÑ"),"n");                            
        patterns.put(Pattern.compile("[ÓÓÖÔòóôõö]"),"o");
        patterns.put(Pattern.compile("œ"),"oe");
        patterns.put(Pattern.compile("[ÙÚÛÜùúûü]"), "u");
        patterns.put(Pattern.compile("[ýÿ]"),"y");
        patterns.put(Pattern.compile("[^a-z A-Z 0-9 \\_ \\+]"),"");
        patterns.put(Pattern.compile(" "),"_");
}

    /* Test 3 (@devconsole's Lookup table) initialization */
static SparseArray<String> homeBrewPatterns=new SparseArray<String>();
/** helper function to fill the map where many different chars map to the same replacement */
static void fillMap(String chars, String replacement) { for (int i=0,len=chars.length(); i<len; i++) homeBrewPatterns.put(chars.charAt(i), replacement); }
static {
    // fill the sparsearray map with all possible substitutions: Any char code gets its equivalent, ie, ä->a. a->a. A->a
    // this also does the toLowerCase automatically. If a char is not in the list, it is forbidden and we skip it.
    fillMap("ÁÀÂÄáàäaàáâãäå","a");
    fillMap("æ","ae");
    fillMap("çÇ","c");
    fillMap("ÈÉÊËèéêë","e");
    fillMap("ìíîïÍÌÎÏ","i");
    fillMap("ñÑ","n");
    fillMap("ÓÓÖÔòóôõö","o");
    fillMap("œ","oe");
    fillMap("ÙÚÛÜùúûü","u");
    fillMap("ýÿ","y");
    fillMap(" ","_");
    for (char c='a'; c<='z'; c++) fillMap(""+c,""+c); // fill standard ASCII lowercase -> same letter 
    for (char c='A'; c<='Z'; c++) fillMap(""+c,(""+c).toLowerCase()); // fill standard ASCII uppercase -> uppercase
    for (char c='0'; c<='9'; c++) fillMap(""+c,""+c); // fill numbers
}

    /** FUNCTION TO TEST #1: Original function, no pattern compilation */ 
public static String makeValidPathName(String rawString) {
    if (rawString==null) return null;
    rawString = rawString.replaceAll("[ÁÀÂÄáàäaàáâãäå]","a");
    rawString = rawString.replaceAll("æ","ae");
    rawString = rawString.replaceAll("çÇ","c");
    rawString = rawString.replaceAll("[ÈÉÊËèéêë]","e");
    rawString = rawString.replaceAll("[ìíîïÍÌÎÏ]","i");
    rawString = rawString.replaceAll("ñÑ","n");                            
    rawString = rawString.replaceAll("[ÓÓÖÔòóôõö]","o");
    rawString = rawString.replaceAll("œ","oe");
    rawString = rawString.replaceAll("[ÙÚÛÜùúûü]", "u");
    rawString = rawString.replaceAll("[ýÿ]","y");
    rawString = rawString.replaceAll("[^a-z A-Z 0-9 \\_ \\+]","");
    rawString = rawString.replaceAll(" ","_");
    return rawString.toLowerCase();
}
/** FUNCTION TO TEST #2: @WCChargin's suggestion: Compile patterns then iterate a map */
public static String makeValidPathName_compiled(String rawString) {
    for (Map.Entry<Pattern, String> e : patterns.entrySet()) {
        rawString=e.getKey().matcher(rawString).replaceAll(e.getValue());
    }
    return rawString.toLowerCase();
}

    /** FUNCTION TO TEST #3: @devconsole's suggestion: Create a LUT with all equivalences then append to a stringbuilder */
public static String makeValidPathName_lut(String rawString) {
    StringBuilder purified=new StringBuilder(rawString.length()); // to avoid resizing
    String aux; // to avoid creating objects inside the for
    for (int i=0, len=rawString.length(); i<len; i++) {
        aux=homeBrewPatterns.get(rawString.charAt(i));
        if (aux!=null) purified.append(aux);
    }
    return purified.toString();
}

    /** FUNCTION TO TEST #4: @Erik Pragt's suggestion on the use of a Normalizer */
public static String makeValidPathName_normalizer(String rawString) {
        return rawString == null ? null
            : Normalizer.normalize(rawString, Form.NFD)
                .replaceAll("\\p{InCombiningDiacriticalMarks}+", "");
}

    /** Test Runner as a Runnable, just do a Handler.post() to run it */

public static Runnable msStringReplacementTest=new Runnable() {

    public void run() {


    String XTAG="REPLACEMENT_TEST";

    Log.d(XTAG, "*** Running Tests");

    int ITERATIONS=1000;

    String[] holder=new String[4];

            /* http://www.adhesiontext.com/ to generate dummy long text ... its late n im tired :) */

    String tester="e arte nací valse ojales i demediada cesé entrañan domó reo ere fiaréis cinesiterapia fina pronto mensuraré la desatufases adulantes toree fusca ramiro hez apolíneo insalvable atas no enorme mí ojo trola chao fas eh borda no consignataria uno ges no arenque ahuyento y daca pío veló tenle baúl ve birria filo rho fui tañe mean taz raicita alimentarías ano defunciones u reabráis repase apreciaran cantorales ungidas naftalina ex guió abomba o escribimos consultarás des usó saudí mercó yod aborrecieses guiri lupia ña adosado jeringara fe cabalgadura tú descasar diseñe amar limarme escobero latamente e oreó lujuria niñez fabularios da inviernen vejé estañarán dictará sil mírales emoción zar claudiquéis ó e ti ñ veintén dañen ríase esmeraras acató noté as mancharlos avisen chocarnos divertidas y relata nuera usé fié élitro baba upa cu enhornan da toa hechizase genesíacos sol fija aplicó gafa pi enes fin asé deal rolar recurran cacen ha id pis pisó democristiano oes eras lañó ch pino fijad ñ quita hondazos ñ determinad vid corearan corrompimiento pamema meso fofas ocio eco amagados pian bañarla balan cuatrimestrales pijojo desmandara merecedor nu asimiladores denunciándote jada ñudos por descifraseis oré pelote ro botó tu sí mejorado compatibilizaciones enyerba oyeses atinado papa borbón pe dé ñora semis prosada luces leí aconteciesen doy colmará o ve te modismos virola garbillen apostabas abstenido ha bajá le osar cima ají adormecéis ñu mohecí orden abrogándote dan acanilladas uta emú ha emporcara manila arribeña hollejo ver puntead ijadeáis chalanesca pechugón silbo arabescos e i o arenar oxidas palear ce oca enmaderen niñez acude topó aguanieves i aconsejaseis lago él roía grafito ceñir jopo nitritos mofe botáis nato compresores ñu asilo amerizan allanándola cuela ó han ice puya alta lío son de sebo antieconómicas alá aceza latitud faca lavé colocándolos concebirlo miserea ñus gro mearé enchivarse";

    long time0=System.currentTimeMillis();
    for (int i=0; i<ITERATIONS; i++) holder[0]=makeValidPathName(tester); // store in an array to avoid possible JIT optimizations
    long elapsed0=System.currentTimeMillis()-time0;

    Log.d(XTAG, "Original REGEX  : "+elapsed0+" ms");

    long time1=System.currentTimeMillis();
    for (int i=0; i<ITERATIONS; i++) holder[1]=makeValidPathName_compiled(tester); // store in an array to avoid possible JIT optimizations
    long elapsed1=System.currentTimeMillis()-time1;

    Log.d(XTAG, "Compiled REGEX  : "+elapsed1+" ms");

    long time2=System.currentTimeMillis();
    for (int i=0; i<ITERATIONS; i++) holder[2]=makeValidPathName_lut(tester); // store in an array to avoid possible JIT optimizations
    long elapsed2=System.currentTimeMillis()-time2;

    Log.d(XTAG, "Character LUT   : "+elapsed2+" ms");

    long time3=System.currentTimeMillis();
    for (int i=0; i<ITERATIONS; i++) holder[3]=makeValidPathName_normalizer(tester); // store in an array to avoid possible JIT optimizations
    long elapsed3=System.currentTimeMillis()-time3;

    Log.d(XTAG, "Java NORMALIZER : "+elapsed3+" ms");

    Log.d(XTAG, "Output 0: "+holder[0]);
    Log.d(XTAG, "Output 1: "+holder[1]);
    Log.d(XTAG, "Output 2: "+holder[2]);
    Log.d(XTAG, "Output 3: "+holder[3]);
    }
};

伙计们,非常感谢您的建议 :) 我喜欢 stackoverflow :)

4

3 回答 3

2

构建一个静态Map<Character,String>映射一个字符到它的替换字符串,即映射'Á'到“a”,'ä'到“a”等。还包括一对一的对应关系,即映射'a'到“ a”等等。您会得到一张最多包含几百个条目的地图。

现在遍历输入字符串的字符并在静态映射中查找替换字符串。如果映射不包含条目,则跳过该字符,否则将替换附加到 StringBuilder。

于 2013-05-08T23:39:09.327 回答
2

如果您必须使用正则表达式,您可以预编译您的模式:

Map<Pattern, String> patterns = new HashMap<Pattern, String>();
{ // initializer block (you could do this in constructor also)
    patterns.put(Pattern.compile("[ÁÀÂÄáàäaàáâãäå]") ,"a");
    rawString = rawString.replaceAll("æ","ae");
    // etc.
}

// later...
for (Map.Entry<Pattern, String> e : patterns) {
    rawString = e.getValue().matcher(rawString).replaceAll(e.getKey());
}

for循环中的行是关键。下面是剖析:

  • e.getValue()从地图键中获取模式
  • .matcher(rawString)获取Matcher模式的对象,将正则表达式的实例与给定的字符串(原始字符串)匹配
  • .replaceAll就像String方法一样工作(我相信String使用这个,实际上)
  • e.getKey()从映射键中获取要替换的值

进一步阅读的链接:

于 2013-05-08T23:11:51.413 回答
1

您可以尝试做的不是使用正则表达式,而是使用Normalizer您可以在此处找到有关它的信息。

从该页面:

import java.text.Normalizer;
import java.text.Normalizer.Form;

// ...

public static String removeAccents(String text) {
    return text == null ? null
        : Normalizer.normalize(text, Form.NFD)
            .replaceAll("\\p{InCombiningDiacriticalMarks}+", "");
}

它并不能解决您的所有需求,但它适用于相当广泛的角色。但是,我建议无论如何都要进行性能测量,以比较这两种解决方案。如果您真的想使用正则表达式解决方案,请先尝试创建一些静态模式,然后再使用匹配器,这样您只会获得创建这些模式一次的开销。

于 2013-05-08T23:07:33.693 回答