本文實(shí)例講述了Java正則匹配中文的方法。分享給大家供大家參考,具體如下:
1、匹配雙引號(hào)間內(nèi)容:
1
2
3
4
5
6
7
8
9
10
|
public void test1() { // 匹配雙引號(hào)間內(nèi)容 String pstr = "\"([^\"]+)\"" ; Pattern p = Pattern.compile(pstr); Matcher m = p.matcher( "\"goodjob\"" ); System.out.println(m.find() ? m.group( 1 ) : "nothing" ); // 測(cè)試中文 m = p.matcher( "\"goodjob里面有中文呢\"" ); System.out.println(m.find() ? m.group( 1 ) : "nothing" ); } |
2、中文內(nèi)容也匹配:
1
2
3
4
5
6
7
8
9
10
|
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" ); // 測(cè)試標(biāo)點(diǎn) m = p.matcher( "\"goodjob還有標(biāo)點(diǎn)!\"" ); System.out.println(m.find() ? m.group( 1 ) : "nothing" ); } |
3、標(biāo)點(diǎn)也匹配:
1
2
3
4
5
6
|
public void test3() { // 標(biāo)點(diǎn)也匹配 Pattern p = Pattern.compile( "\"([^\"|[\u4e00-\u9fa5\ufe30-\uffa0]]+)\"" ); Matcher m = p.matcher( "\"goodjob還有標(biāo)點(diǎn)!\"" ); System.out.println(m.find() ? m.group( 1 ) : "nothing" ); } |
上面三個(gè)程序的輸出如下:
1
2
3
4
5
|
goodjob nothing goodjob里面有中文呢 nothing goodjob還有標(biāo)點(diǎn)! |
希望本文所述對(duì)大家java程序設(shè)計(jì)有所幫助。