1 // 非负整数:“^\d+$ ” 2 // 正整数: “ ^[0-9]*[1-9][0-9]*$” 3 // 非正整数: “ ^((-\d+)|(0+))$” 4 // 整数: “ ^-?\d+$” 5 // 英文字符串: “ ^[A-Za-z]+$” 6 // 英文字符数字串: “ ^[A-Za-z0-9]+$” 7 // 英数字加下划线串: “^\w+$” 8 // E-mail地址:“^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$” 9 // URL:“^[a-zA-Z]+://(\w+(-\w+)*)(\.(\w+(-\w+)*))*(\?\s*)?$” s1
//正则 : 对字符串的匹配,判断是否是某种格式
//正则表达式也是一段字符串,里面放的是匹配的规则
//正则规则: // \d 数字 // \D 非数字 // \w 数字+英文+下划线 // \W 非数字+英文+下划线 // \s 空格 // \S 非空格
// 正则中的特殊符号
// ? 0-1次
// + 最少一次
// * 任意次
// . 任意字符
--实例
String str=""; // 匹配英文名字 Join|join|marry /** str="Join"; if(str.matches("Join|join|marry")) { System.out.println("对的"); }else { System.out.println("错的"); } **/ // 用戶名:只能是英文 6~12 位 /** str="yrfdfaaff"; System.out.println(str.matches("[a-z]{6,12}")); **/ // 用戶名:只能是數字 6~12位(不能以0开始) /** str="0324311"; System.out.println(str.matches("[1-9][0-9]{5,11}")); **/ // 用戶名:英文+數字+下劃綫 6~12位(必须以字母开头) /** str="a0324311_"; System.out.println(str.matches("[a-zA-Z][a-zA-Z0-9_]{5,11}")); **/ // 匹配密码:6位的数字 不能以0開頭 /** str="1231316"; System.out.println(str.matches("[1-9]\\d{5}")); **/ // 匹配用户名: // 必须英文,数字,下划线的字符 // 长度在3-4之间 // 必須以 admin 或者 sa 開頭 /** str="admin123"; System.out.println(str.matches("(admin|sa)\\w{3,4}")); **/ // 1-50位并且只能是字母或数字 // [0-9a-zA-Z]{1,50} // 密码8-16位且可以是数字与字母的组合 // [0-9a-zA-Z]{8,16} // 正则中的特殊符号 // ? 0-1次 // + 最少一次 // * 任意次 // . 任意字符 // 密码8-16位且是数字与字母的组合 // (必须有数字+字母) // [a-zA-Z0-89]{8,16} // 匹配用户名: // 必须是abcdefg02468中的字符组成 // 长度在6位以上 // [a-g02468]{6,} // 匹配abcdefg 选择一个或0个 // [a-g]? // 匹配一个任意的数字 // 避免负数 // 避免0打头的 /** str = "123"; System.out.println(str.matches("0|-?[1-9]\\d*")); **/ // 匹配小數 /** str = "123.0"; boolean f = str.matches("\\d+[.]\\d+"); System.out.println(f); **/ // 匹配负小數 // -?\\d+[.]\\d+ // 匹配邮箱: @ . // 123@qq.com // www.123@qq.com /** str = "123@qq.com"; boolean f = str.matches("(\\w+[.])?\\w+@\\w+[.](gov|net|cn|com)"); System.out.println(f); **/ // 月份 1-12 // 1-9 -> [1-9] // 10-12 -> 1[0-2] /** str = "13"; boolean f = str.matches("[1-9]|1[0-2]"); System.out.println(f); **/ // 匹配日期 1-31 // 1-9 -> [1-9] // 10-29 -> [1-2][0-9] // 30-31 -> 3[0-1] /** str = "13"; boolean f = str.matches("[1-9]|[1-2][0-9]|3[0-1]"); System.out.println(f); **/ // 匹配年龄 1-150 // 1 - 9 [1-9] // 10 - 99 [1-9]\d // 100 - 149 1[0-4]\d // 150 150 //[1-9]|[1-9]\d|1[0-4]\d|150 // 匹配手机号码 // 位数:11 // 1开头 2位:3456789 // 1(3\d|4[5-9]|5[0-35-9]|6[567]|7[0-8]|8\d|9[0-35-9])\d{8}