正则表达式基础语法
- 三个括号的含义
- [] 指定范围内的任意的一个字符 [0-9a-zA-Z] 0-9和a-z和A-Z范围内的所有数
- {} 指定内容重复的次数 {5} 出现5次
- ()分组 将若干部分的字符串作为一个整体进行操作 123{10} (123){10}
- \d : 表示任意一个数字(0-9)
- [0-9] : 表示0-9之间任意的一个数字
- {n-m} : 出现n–m次 m、n均为非负整数 其中n<=m 最少匹配n次且最多匹配m次,注意在逗号之间的两个数之间不能有空格
- [^123] 代表除了1、2、3之外的任何字符
- \d [0-9] 代表0-9之间的任意一个数
- \D [^0-9] 代表任何一个非数字字符
- \w [0-9a-zA-Z_] 代表任何一个数或字母或下划线
- \W [^0-9a-zA-Z] 代表不可用于标识符的字符
- \s 代表空白字符 (空格 制表符\t 换行符 \n)
- \S 非空白字符
- \b 匹配单词的开始或者结束 \b[a-zA-Z]\b
- . 可以匹配除了换行符(\n)以外的任意一个字符
- \. 只匹配 .
- $ 匹配字符串的开始
- ^ 匹配字符串的结束
- | 或
-
- 出现一次或者多次
-
- 出现0次或多次
- ? 出现0次或者1次
- {n} 正好出现n次
{n,} 至少出现n次
- 验证QQ号
public static void main(String[] args) { checkQQ("1234567890"); } public static void checkQQ(String qq){ //[1-9] 1-9的范围 // \\d 代表任意的数字(0-9) //{4,9} 0-9的数字出现4-9次 String regex="[1-9]\\d{4,9}"; boolean flag=qq.matches(regex); if(flag){ System.out.println("格式正常"); }else{ System.out.println("格式有误"); } }
验证手机号
public static void main(String[] args) { String str="134012345691"; // 1代表数字1 // [3578] 只能输入3、5、7、8这几个数 // \\d 代表0-9 之间任意的数 // {9} 正好出现的次数 String regex="1[3578]\\d{9}"; boolean flag=str.matches(regex); if(flag){ System.out.println("格式正确"); }else{ System.out.println("格式错误"); } }
验证固定电话
? {0,1} 代表出现0-1次
public static void main(String[] args) { String str="8800127"; // ? {0,1} 出现0-1次 String regex="(0\\d{2,3}-)?\\d{7,8}"; boolean flag=str.matches(regex); if(flag){ System.out.println("格式正确"); }else{ System.out.println("格式错误"); } }
String类对正则表达式的支持
boolean mathes(String regex) 告知此字符串是否匹配给定的正则表达式
String str="2"; //只能出现1-3之间的数字 String regex="[1-3]"; boolean flag=str.matches(regex); System.out.println(flag);
String replaceAll(String regex,String replacement) 使用给定的 replacement 替换此字符串所有匹配给定的正则表达式的子字符串
String str="sadasaggsfasdfasf123456123456789"; System.out.println(str); String replaceAll = str.replaceAll("[a-z]", "#"); System.out.println(replaceAll); 运行结果 : sadasaggsfasdfasf123456123456789 #################123456123456789
String replaceFirst(String regex, String replacement) 使用给定的 replacement 替换此字符串匹配给定的正则表达式的第一个子字符串。
String str="sadasaggsfasdfasf123456123456789"; System.out.println(str); //String replaceAll = str.replaceAll("[a-z]", "#"); String replaceFirst = str.replaceFirst("[0-9]", "*"); System.out.println(replaceFirst); 运行结果 : sadasaggsfasdfasf123456123456789 sadasaggsfasdfasf*23456123456789
String[] split(String regex) 根据给定正则表达式的匹配拆分此字符串。
String str="My father was a self-taught mandolin player. He was one of the best string instrument players in our town."; String[] split = str.split("[.,\\s]"); for(String s:split){ System.out.println(s); }
*使用Pattern中的compile(String regex)方法和matcher(CharSequence input)方法分割字符串
String str="My,father,was.a self-taught mandolin player. He was one of the best string instrument players in our town."; String regex="\\b[a-z]+\\b"; Pattern compile = Pattern.compile(regex); Matcher matcher = compile.matcher(str); while(matcher.find()){ System.out.println(matcher.group()+"\t"); }