unicode 字符串转 表达的字符

package com.yt17lu.commons;

import java.util.Scanner;

public class UnicodeParse {
	/**
	 *
	 * @param dataStr
	 *            接受的unicode 字符串
	 * @return 代表的字符串
	 * @throws 如果输入的格式不是u后跟2-4位16进制则抛出格式错误
	 */
	public static String parse(String dataStr) {
		boolean matches = dataStr.matches("^(\\\\u\\p{XDigit}{2,4})*$");
		if (!matches) {
			throw new RuntimeException(dataStr + ",unicode字符串格式错误");
		}
		int start = 0;
		int end = 0;
		StringBuffer buffer = new StringBuffer();
		int len = dataStr.length();
		while (start < len) {
			end = dataStr.indexOf("\\u", start + 2);
			end = (end == -1) ? len : end;
			String temp = dataStr.substring(start + 2, end);
			buffer.append((char) Integer.parseInt(temp, 16));
			start = end;
		}
		return buffer.toString();
	}

	public static void main(String[] args) {
		Scanner input = new Scanner(System.in);
		System.out.println("请输入字符:");
		String code = input.next();
		System.out.println(UnicodeParse.parse(code));
	}
}

你可能感兴趣的:(unicode)