java中的正则表达式的使用

常用类与常用方式实例:邮箱验证示例

public static void main(String[] args) {
    // 要验证的字符串
    String str = "[email protected]";
    // 邮箱验证规则
    String regEx = "[a-zA-Z_]{1,}[0-9]{0,}@(([a-zA-z0-9]-*){1,}\\.){1,3}[a-zA-z\\-]{1,}";
    // 编译正则表达式
    Pattern pattern = Pattern.compile(regEx);
    // 忽略大小写的写法
    // Pattern pat = Pattern.compile(regEx, Pattern.CASE_INSENSITIVE);
    Matcher matcher = pattern.matcher(str);
    // 字符串是否与正则表达式相匹配
    boolean rs = matcher.matches();
    System.out.println(rs);
}

解析:上面一共涉及两个类,pattern与matcher,其中pattern.compile用于设置正则表达式规则,matcher用于存放对比的字符串,最后调用matcher.matches()方法得到相应校验结果;

java中使用正则表达式的途径:

1.在String的split方法中

 1 public static void main(String[] args) {
 2         //将一组数字字符串,拆分称为一组数字数组
 3         String a = "9 8 7 65 43";
 4         //验证是否是字符
 5         char charat;
 6         for(int i=0;i<a.length();i++){
 7             charat = a.charAt(i);
 8             if(!Character.isDigit(charat) && charat!=' '){
 9                 System.out.println("包含非数字字符");
10             }
11         }
12         //利用正则表达式拆分,其中需要注意此正则表达式中是有一个空格的,加上后面的{1,},表示匹配1到多次空格;
13         String[] intString = a.split(" {1,}");
14         int[] ints = new int[intString.length];
15         System.out.println(Arrays.toString(intString));
16         //进行格式转换
17         for(int i=0;i<intString.length;i++){
18             ints[i]=Integer.valueOf(intString[i]);
19         }
20         System.out.println(Arrays.toString(ints));
21 }

猜你喜欢

转载自www.cnblogs.com/silence-fire/p/9018496.html