Java全角字符串转换为半角字符串

清华大佬耗费三个月吐血整理的几百G的资源,免费分享!....>>>

如下是用正则表达式实现的java全角转半角代码片段:

import java.util.regex.*;

public static String replaceDBC2SBC(String input) {
    Pattern pattern = Pattern.compile("[\u3000\uff01-\uff5f]{1}");

    Matcher m = pattern.matcher(input);
    StringBuffer s = new StringBuffer();
    while (m.find()) {
        char c = m.group(0).charAt(0);
        char replacedChar = c == ' ' ? ' ' : (char) (c - 0xfee0);
        m.appendReplacement(s, String.valueOf(replacedChar));
    }

    m.appendTail(s);

    return s.toString();
}

单元测试代码如下:

    @Test
    public void testReplaceQuanjiao() {
        String text = "ab123w我们3jkjkdfdf444eeee";

        String expected = "ab123w我们3jkjkdfdf444eeee";
        String actual = replaceDBC2SBC(text);

        assertEquals(expected, actual);
    }