Java 正则表达式
什么是正则表达式
- 正则表达式使用单个字符串来描述、匹配一系列符合某个句法规则的 字符串 。
为什么要学习正则表达式
- 方便提取一些文章中的字符,数字,单词,以及其他的一些数据
- 可以替换一些字符串的内容
- 可以分割字符串
- 可以用来验证一些输入或者某些模式是否匹配
正则表达式的使用
-
正则表达式的基本语法
-
转义符(\\):在java中(\\)在其他一些语言中代表\
-
需要用到转义符的字符有(.*+()$/?[]^{ })
private static void test() { //.*+()$/\?[]^{ } System.out.println(".".matches("\\.")); System.out.println("*".matches("\\*")); System.out.println("[".matches("\\[")); }
-
-
字符匹配符
符号 解释 [ ] 可接受字符列表(可以接受里面任意一个) [^] 不可接受字符列表 . 匹配除\n之外任何字符 \\d 匹配单个数字 \\D 匹配除单个数字 \\w 匹配数字,字母,下划线 \\W 匹配除数字,除字母,除下划线 //匹配a-z之间任意一个字符 System.out.println("d".matches("[a-z]")); ///匹配abc,不区分大小写 System.out.println("D".matches("(?i)[a-z]")); //匹配除a-z的字符 System.out.println("2".matches("[^a-z]")); //匹配不是0-9的一个字符 System.out.println("%".matches("\\D")); //匹配0-9的一个字符 System.out.println("4".matches("\\d")); //匹配任意的一个英文字符,数字还有下划线 System.out.println("4".matches("\\w")); //匹配除英文字符,数字还有下划线的一个字符 System.out.println("$".matches("\\W")); //匹配空格字符(空格,制表符)一个字符 System.out.println("\t".matches("\\s")); //匹配除空格字符(空格,制表符)一个字符 System.out.println("a".matches("\\S"));
-
选择匹配符
System.out.println("a".matches("a|b"));
-
限定符
符号 解释 * 指定字符重复0次或n次 + 指定字符重复1次或n次 ? 指定字符重复0次或1次 {n} 只能输入n个字符 {n,} 指定至少n个匹配 {n,m} 指定至少匹配n个,最多匹配m个 String content = "111111111aaaaaahelloaaa111"; // String regStr = "a{3}";//表示匹配aaa // String regStr = "1{4}";//表示匹配4个1 // String regStr = "\\d{4}";//表示匹配4位的数字字符1 // String regStr = "a{3,4}";//表示匹配aaa或者aaaa // String regStr = "\\d{2,5}";//表示匹配两位数或者三位数,四位数,五位数 // String regStr = "a+";//表示匹配多个a或者一个a // String regStr = "1*";//表示匹配多个a或者0个a String regStr = "a1?";//表示匹配a或者a1 Pattern compile = Pattern.compile(regStr); Matcher matcher = compile.matcher(content); while (matcher.find()){ System.out.println(matcher.group(0)); }
-
定位符
符号 解释 ^ 从^的字符开头 $ 从$的字符结尾 \\b 匹配目标字符串边界 \\B 匹配目标字符串非边界 String content = "1230abc"; // String regStr = "^[0-9]+[a-z]*";//以数字开头后接任意小写字母字符串 // String regStr = "^[0-9]+[a-z]+$";//以数字开头必须以一个字母结尾 String regStr = "bc\\b";//表示匹配边界的bc Pattern compile = Pattern.compile(regStr); Matcher matcher = compile.matcher(content); while (matcher.find()){ System.out.println(matcher.group(0)); }
-
非捕获
(?:xxx) 匹配xxx但不捕获该匹配的子表达式 (?=xxx) 匹配xxx前的字符 (?!xxx) 不匹配xxx前的字符 String content = "开发喵一班 开发喵二班 开发喵三班 你好五班"; // String regStr = "开发喵(?:三班|二班|一班)"; // String regStr = "开发喵(?=三班|二班)"; String regStr = "你好(?!三班|二班|一班)"; Pattern pattern = Pattern.compile(regStr); Matcher matcher = pattern.matcher(content); while (matcher.find()){ System.out.println(matcher.group(0)); }
验证是不是一个整数或者小数
-
//验证是不是一个整数或者小数 private static void fractions() { String content = "-1078"; String regStr = "^[+-]?([1-9]\\d*|0)(\\.([0-9]+))?"; boolean matches = Pattern.matches(regStr, content); System.out.println(matches); }
-
反向引用
private static void test3() { String content = "1212"; String regStr = "(\\d)(\\d)\\1\\2"; Pattern pattern = Pattern.compile(regStr); Matcher matcher = pattern.matcher(content); while (matcher.find()){ System.out.println(matcher.group(0)); } }
-