只能輸入中文
/** * 22.驗證漢字 * 表達式 ^[/u4e00-/u9fa5]{0,}$ * 描述 只能漢字 * 匹配的例子 清清月兒 */ @Test public void a1() { Scanner sc = new Scanner(System.in); String input = sc.nextLine(); String regex = "^[//u4e00-//u9fa5]*$"; Matcher m = Pattern.compile(regex).matcher(input); System.out.println(m.find()); sc.close(); }PS:下面看下Java中要匹配中文的正則表達式可以有兩種寫法:一是使用unicode中文碼;二是直接使用漢字字符;
例:
(1)String str = "晴";
String regexStr = "[/u4E00-/u9FA5]";str.regex(regexStr);
(2)String str = "晴";