建议放大观看
入门案例 理解(位置 类型 个数)的含义
基本语法
字符表补充:
java 中使用正则, 需要是用”\“ 脱去特殊字符
java中有两种方式使用 正则 ,一种是patton & matcher ; 一种是String , 但本质是一样的。String 底层是patton & Matche
java匹配字符实例(使用正则对象)
@Test public void e() { // 有一个字符串,其中包含中文字符、英文字符和数字字符,请统计和打印出各个字符的个数 int num = 0; int num1 = 0; int num2 = 0; Pattern compile = Pattern.compile( "[\u4E00-\u9FA5]" ); Pattern compile1 = Pattern.compile( "[\\d]" ); Pattern compile2 = Pattern.compile( "[a-zA-Z]" ); String a = "我的世是界是abc圆的1234567"; for (int i = 0; i < a.length(); i++) { Matcher matcher = compile.matcher( a.charAt( i ) + "" ); Matcher matcher1 = compile1.matcher( a.charAt( i ) + "" ); Matcher matcher2 = compile2.matcher( a.charAt( i ) + "" ); if (matcher.find()) { num++; } if (matcher1.find()) { num1++; } if (matcher2.find()) { final String a1 = matcher2.group( 0 ); num2++; } } System.out.println( "汉字的个数是:" + num ); System.out.println( "字母的个数是:" + num1 ); System.out.println( "数字的个数是:" + num2 ); }
java 语言分组实例 (使用正则对象)
@Test public void ss(){ Pattern pattern = Pattern. compile ("^(\\d{3,4})\\-(\\d{6,8})$") ; Matcher matcher = pattern . matcher ("010-12345678") ; if (matcher . matches () ){ String whole = matcher . group(0); // "010-12345678". 0表示匹配的整个字符串 string areaCode = matcher. group(1); // "010",1表示匹配的第1个子串 String telNumber = matcher. group(2); // "12345678", 2表示匹配的第2个子串 } }
java 中文查找与替换(使用String方法)
@Test public void d() { String a = "我的世是界是圆的1234567"; String regexStr = "[\u4E00-\u9FA5]*\\d*"; if (a.matches( regexStr )) { a = a.replace( '是', '-' ); System.out.println( a ); } }
java 清洗数据(使用String方法)
@Test public void add() { String s ="a.b。1.2A"; String[] split = s.split( "\\.|。|A$" ); String s1 = Arrays.toString( split ); System.out.println(s1); }
附录:
正则在LInux 中的使用推荐陈思齐博客
https://www.cnblogs.com/chensiqiqi/p/6285060.html
本文有借鉴廖雪峰教学B站教学视频
https://www.bilibili.com/video/av74394062?from=search&seid=631167244202567059
来源:https://www.cnblogs.com/rainbowbridge/p/12543883.html