码迷,mamicode.com
首页 > 其他好文 > 详细

正则表达式

时间:2017-04-30 01:02:37      阅读:212      评论:0      收藏:0      [点我收藏+]

标签:str   括号   gre   install   mini   eal   支付   规则   开始   

正则表达式:用一组特殊的字符描述的一个字符串格式,用来匹配一组字符串并判断是否符合格式要求。正则表达式就是记录文本规则的代码,只关注格式正确,很少关注内容有效

字符集合:

 “[a-z]”   表示a到z的任意一个字符

“[abc]”    表示abc中任意一个字符

“[^abc]”  表示除了abc外任意一个字符

“[a-z0-9]”       表示a到z之间和0到9之间字符

“[a-z]+”  表示由1个或多个a-z字符组成的字符串

 1 /**
 2  *    字符串支付正则表达式的方法1
 3  *    匹配格式
 4  * @author Administrator
 5  *
 6  */
 7 public class demo01 {
 8     public static void main(String[] args) {
 9         /*
10          * 匹配邮箱
11          * [a-zA-Z0-9_]+@[a-zA-Z0-9_]+(\.[a-zA-Z0-9])+
12          */
13         String str = "[a-zA-Z0-9_]+@[a-zA-Z0-9_]+(\\.[a-zA-Z0-9])+";
14         String mail = "like@gmail.com.cn";//不是邮箱
15         /*
16          * Java中match方法是全匹配的,
17          */
18         boolean match = mail.matches(str);
19         if(match){
20             System.out.println("是邮箱");
21         }else{
22             System.out.println("不是邮箱");
23         }
24         
25         
26     }
27 }

 

预定义字符集:

“.”          表示任意一个字符

“\d”        0到9任意一个字符[0-9]

“\w”        单词字符,相当于[a-zA-Z0-9]

“\s”         空白字符,相当于[\t\n\f\r]

“\D”        非数字字符

以此类推

package APIday03;
/**
 * 身份证验证
 * @author Administrator
 *
 */
public class demo02 {
    public static void main(String[] args) {
        /*
         * \d{17}[0-9xX]
         */
        String regex = "\\d{17}[0-9xX]";
        
        String id = "12345678901234567x";
        
        if(id.matches(regex)){
            System.out.println("是身份证号");
            
        }else{System.out.println("不是身份证号");}
    }
}

 

数量词:

X?          0到1个X

X*          0到任意多个X

X+          1到任意多个X

X{n}      n次以上个X

X{n,}     n次以上个X

X{n,m}   n到m个X

 

“()”分组,括号里面的为一个整体

边界匹配:

“^”         代表字符串开始

“$”         代表字符串结束

  String replaceAll(Stirng regex,String replace): 将字符串中满足正则表达式的部分替换为给定内容

1 public class demo04 {
2     public static void main(String[] args){
3         String str = "ingredident12vigorously23installment93";
4         str = str.replaceAll("\\d+","#num#");
5         System.out.println(str);//ingredident#num#vigorously#num#installment#num#
6         
7     }
8 }

String spilt(String regex):
 将当前字符串中满足正则表达式的部分拆分

 1 public class demo03 {
 2     public static void main(String[] args) {
 3         String str = "students,teachers,vigorous";
 4         String[] array = str.split(",");
 5         /*
 6          *students
 7          *teachers
 8          *vigorous
 9          */
10         for(int i = 0;i<array.length;i++){
11             System.out.println(array[i]);
12         }
13     }
14 }

 

正则表达式

标签:str   括号   gre   install   mini   eal   支付   规则   开始   

原文地址:http://www.cnblogs.com/zflovezk9/p/6786600.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!