正则表达式:
符合一定规定的表达式。
作用:用于专门操作字符串。
特点:实际上就是一些特定的符号来表示一些代码操作。
好处:简化书写,提高开发效率。
弊端:符号定义越多,正则越长,阅读性越差。
下面是正则表达式的一些规则。[0-9]可以用\d来代替
{0,1}可以用?代替
匹配:
校验手机号小程序:
手机号段13、15、18
package com.xiaozhi.regex;
public class Test {
public static void main(String[] args) {
String str="13553123456";
String regex="1[358]\\d{9}";
System.out.println(str.matches(regex));
}
}
切割:
按照叠词切割字符串:
( . ) \\ 1括号的意思是分组,后面的1是第一组的意思
package com.xiaozhi.regex;
public class Test {
public static void main(String[] args) {
String str="gffadgggfag";
String regex="(.)\\1+";
String[] arr=str.split(regex);
for(String string:arr){
System.out.println(string);
}
}
}
替换:
$1的意思是将第一个分组的中的字符取出
package com.xiaozhi.regex;
public class Test {
public static void main(String[] args) {
String str="gffadgggfag";
String regex="(.)\\1+";
System.out.println(str.replaceAll(regex,"$1"));
}
}
获取:
package com.xiaozhi.regex;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Test {
public static void main(String[] args) {
String str="ming tian jiu yao fang jia le ,wo men";
String regex="\\b[a-z]{4}\\b";
//将正则表达式封装成对象
Pattern pattern=Pattern.compile(regex);
//让正则表达式与字符串相关联,获取匹配器对象
Matcher matcher=pattern.matcher(str);
while(matcher.find()){//尝试查找与该模式匹配的输入序列的下一个子序列。
System.out.println(matcher.group());//返回由以前匹配操作所匹配的输入子序列。
System.out.println(matcher.start()+"............."+matcher.end());//返回以前匹配操作所匹配的输入子序列的偏移量
}
}
}
练习一:
package com.xiaozhi.regex;
public class Test2 {
public static void main(String[] args) {
String str="我我........我我.......我要.........学学.........编编..............编程";
str=str.replaceAll("\\.","");
String regex="(.)\\1+";
str=str.replaceAll(regex, "$1");
System.out.println(str);
}
}
将ip地址进行地址段顺序的排序
package com.xiaozhi.regex;
import java.util.Arrays;
public class Test3 {
public static void main(String[] args) {
String ip = "192.68.1.254 102.49.23.013 10.10.10.10 2.2.2.2 8.109.90.30";
ip=ip.replaceAll("(\\d+)","00$1");
ip=ip.replaceAll("0*(\\d{3})","$1");
System.out.println(ip);
String[] array=ip.split(" ");
Arrays.sort(array);
for(String str:array){
System.out.println(str);
}
}
}