如下是用正则表达式实现的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); }
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/tech/pnotes/11004.html