本文實例講述了Java正則匹配中文的方法。分享給大家供大家參考,具體如下:
1、匹配雙引號間內容:
1
2
3
4
5
6
7
8
9
10
|
public void test1() { // 匹配雙引號間內容 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、中文內容也匹配:
1
2
3
4
5
6
7
8
9
10
|
public void test2() { // 中文內容也匹配 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、標點也匹配:
1
2
3
4
5
6
|
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" ); } |
上面三個程序的輸出如下:
1
2
3
4
5
|
goodjob nothing goodjob里面有中文呢 nothing goodjob還有標點! |
希望本文所述對大家java程序設計有所幫助。