Java正則匹配中文的方法實例分析
本文實例講述了Java正則匹配中文的方法。分享給大家供大家參考,具體如下:
1、匹配雙引號間內(nèi)容:
public void test1() {
// 匹配雙引號間內(nèi)容
String pstr = "\"([^\"]+)\"";
Pattern p = Pattern.compile(pstr);
Matcher m = p.matcher("\"goodjob\"");
System.out.println(m.find() ? m.group(1) : "nothing");
// 測試中文
m = p.matcher("\"goodjob里面有中文呢\"");
System.out.println(m.find() ? m.group(1) : "nothing");
}
2、中文內(nèi)容也匹配:
public void test2() {
// 中文內(nèi)容也匹配
String pstr = "\"([^\"|[\u4e00-\u9fa5]]+)\"";
Pattern p = Pattern.compile(pstr);
Matcher m = p.matcher("\"goodjob里面有中文呢\"");
System.out.println(m.find() ? m.group(1) : "nothing");
// 測試標點
m = p.matcher("\"goodjob還有標點!\"");
System.out.println(m.find() ? m.group(1) : "nothing");
}
3、標點也匹配:
public void test3() {
// 標點也匹配
Pattern p = Pattern.compile("\"([^\"|[\u4e00-\u9fa5\ufe30-\uffa0]]+)\"");
Matcher m = p.matcher("\"goodjob還有標點!\"");
System.out.println(m.find() ? m.group(1) : "nothing");
}
上面三個程序的輸出如下:
goodjob nothing goodjob里面有中文呢 nothing goodjob還有標點!
PS:這里再為大家提供2款非常方便的正則表達式工具供大家參考使用:
JavaScript正則表達式在線測試工具:
http://tools.jb51.net/regex/javascript
正則表達式在線生成工具:
http://tools.jb51.net/regex/create_reg
希望本文所述對大家java程序設(shè)計有所幫助。
相關(guān)文章
SpringBoot集成JWT的工具類與攔截器實現(xiàn)方式
這篇文章主要介紹了SpringBoot集成JWT的工具類與攔截器實現(xiàn)方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-01-01
SpringBoot集成antlr實現(xiàn)詞法和語法分析
Antlr4 是一款強大的語法生成器工具,可用于讀取、處理、執(zhí)行和翻譯結(jié)構(gòu)化的文本或二進制文件,基本上是當前 Java 語言中使用最為廣泛的語法生成器工具,本文給大家介紹了SpringBoot集成antlr實現(xiàn)詞法和語法分析,需要的朋友可以參考下2024-06-06
SpringMVC+Spring+Mybatis實現(xiàn)支付寶支付功能的示例代碼
這篇文章主要介紹了SpringMVC+Spring+Mybatis實現(xiàn)支付寶支付功能的示例代碼,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-05-05

