java匹配中文的正則表達式 – JAVA編程語言程序開發技術文章

Java的正則表達式如何匹配中文字符呢?

 

下面給出例子讓我們匹配所有的中文字符:

 

Java代碼 
public static void regxChinese(){  
       // 要匹配的字符串     
       String source = "<span title='5 星級酒店' class='dx dx5'>";  
       // 將上面要匹配的字符串轉換成小寫     
      // source = source.toLowerCase();     
       // 匹配的字符串的正則表達式     
       String reg_charset = "<span[^>]*?title=\'([0-9]*[\\s|\\S]*[\u4E00-\u9FA5]*)\'[\\s|\\S]*class=\'[a-z]*[\\s|\\S]*[a-z]*[0-9]*\'";       
   
       Pattern p = Pattern.compile(reg_charset);     
       Matcher m = p.matcher(source);     
       while (m.find()) {     
        System.out.println(m.group(1));  
       }  

 public static void regxChinese(){
        // 要匹配的字符串  
        String source = "<span title='5 星級酒店' class='dx dx5'>";
        // 將上面要匹配的字符串轉換成小寫  
       // source = source.toLowerCase();  
        // 匹配的字符串的正則表達式  
        String reg_charset = "<span[^>]*?title=\'([0-9]*[\\s|\\S]*[\u4E00-\u9FA5]*)\'[\\s|\\S]*class=\'[a-z]*[\\s|\\S]*[a-z]*[0-9]*\'";    
 
        Pattern p = Pattern.compile(reg_charset);  
        Matcher m = p.matcher(source);  
        while (m.find()) {  
         System.out.println(m.group(1));
        }
 }

輸出如下:

 

Html代碼 
5 星級酒店 

5 星級酒店

 

註解:匹配所有中文字符正則表達式如下:

 

Java代碼 
[\u4E00-\u9FA5]漢字﹐[\uFE30-\uFFA0]全角字符 

[\u4E00-\u9FA5]漢字﹐[\uFE30-\uFFA0]全角字符

所以說,Java的正則表達式是可以匹配中文字符的,同時,用中文字符來寫表達式也是可以的.比如說上面的要匹配下面的字符:

 

Html代碼 
5 星級酒店 

5 星級酒店

上面例子中的中文正則表達式還可以寫成如下的形式:

 

 

Java代碼 
String reg_charset = "<span[^>]*?title=\'([0-9]*[\\s|\\S]*星級酒店)\'[\\s|\\S]*class=\'[a-z]*[\\s|\\S]*[a-z]*[0-9]*\'";      

 String reg_charset = "<span[^>]*?title=\'([0-9]*[\\s|\\S]*星級酒店)\'[\\s|\\S]*class=\'[a-z]*[\\s|\\S]*[a-z]*[0-9]*\'";    
 

但是為瞭靈活性,最好就別用中文去寫正則表達式,這樣寫太死瞭,一個不小心多個空格都會匹配不瞭..

 摘自 hpjianhua
 

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *