代码之家  ›  专栏  ›  技术社区  ›  BuddyJoe

JavaScript正则表达式到Java正则表达式-替换和lambda

  •  1
  • BuddyJoe  · 技术社区  · 14 年前

    把这个代码翻译成Java的最好方法是什么? (名为“将字母数字电话号码转换为所有数字”的部分) http://lawrence.ecorp.net/inet/samples/regexp-format.php

    因为Java还没有lambda…对于string.replace,最好的方法是什么?

    2 回复  |  直到 14 年前
        1
  •  2
  •   bobince    14 年前

    return phoneStr.replace(/[a-zA-Z]/g, function(m) {
        var ix= m[0].toLowerCase().charCodeAt(0)-0x61; // ASCII 'a'
        return '22233344455566677778889999'.charAt(ix);
    });
    

    StringBuffer b= new StringBuffer();
    Matcher m= Pattern.compile("[A-Za-z]").matcher(phoneStr);
    while (m.find()) {
        int ix= (int) (m.group(0).toLowerCase().charAt(0)-'a');
        m.appendReplacement(b, "22233344455566677778889999".substring(ix, ix+1));
    }
    m.appendTail(b);
    return b.toString();
    

    char[] c= phoneStr.toLowerCase().toCharArray();
    for (int i= 0; i<c.length; i++)
        if (c[i]>='a' && c[i]<='z')
            c[i]= "22233344455566677778889999".charAt((int) (c[i]-'a'));
    return new String(c);
    
        2
  •  1
  •   Colin Hebert    14 年前

    String replaceCharsByNumbers(String stringToChange) {
        return stringToChange
                .replace('a', '2')
                .replace('b', '2')
                .replace('c', '2')
                .replace('d', '3')
                .replace('e', '3')
                .replace('f', '3')
                .replace('g', '4')
                .replace('h', '4')
                .replace('i', '4')
                .replace('j', '5')
                .replace('k', '5')
                .replace('l', '5')
                .replace('m', '6')
                .replace('n', '6')
                .replace('o', '6')
                .replace('p', '7')
                .replace('q', '7')
                .replace('r', '7')
                .replace('s', '7')
                .replace('t', '8')
                .replace('u', '8')
                .replace('v', '8')
                .replace('w', '9')
                .replace('x', '9')
                .replace('y', '9')
                .replace('z', '9');
    }