package en.iteast.regular;
public class RegexTest {
/**
*
* @param args
*/
public static void main(String[] args) {
matchesDemo();
splitDemo();
replaceDemo();
}
/**
* 检查是否匹配
*/
public static void matchesDemo() {
//需求:校验手机号码是否正确
String tel = "12800001111";
String regex = "1[358]\\d{9}";
/*
*\\d{9}:保证后9位为数字即可
*/
boolean b = tel.matches(regex);
System.out.println(tel+":"+b);
}
/**
* 按照规定进行替换
* ?待理解
*/
public static void replaceDemo() {
// String temp = "15698382939";
// temp = temp.replaceAll("(\\d{3})\\d{4}(\\d{4})", "$1****$2");
// System.out.println(temp);
// /*
// * $可以在多参数时,后面的参数可以通过$编号的形式取到前一个参数的组。
// */
// String temp = "qwe###hsdhk$$$$$$shjkkqqqqq";
// temp = temp.replaceAll("(.)\\1+", "&");//>>>qwe&hsdhk&shj&&
String temp = "qwe###hsdhk$$$$$$shjkkqqqqq";
temp = temp.replaceAll("(.)\\1+", "$1");//>>>qwe#hsdhk$shjkq
System.out.println(temp);
}
/**
* 按照规定进行切割
*/
public static void splitDemo() {
// 1.
// String temp = "zhangsan lisi wangwu";
// String regex = " +";//+代表无穷,前面是空格,也就是说空格数大于2时,就以此空格进行切割
//2.
// String temp = "zhangsan.lisi.wangwu";
// String regex = "\\.";//以.作为切割
/*
* \\.说明:
* 应为 . 在正则表达式代表任意字符,需要用\\对其进行转译
*/
String temp = "kh$$$$$389####djsjh@@@@";
String regex = "(.)\\1+";//第一组全是.,用第一组进行切割
/*
* (.)\\1+说明:
* 为了实现规则的复用,用()将需要复用的规则封装,就称为正则表达式中的组,每一个组
* 都有编号,从1开始。通过使用编号就可以复用对应组的规章内容。注意:标号必须用到
* 组的后面。也就是说:先封装完,再调用。
*
*
*/
String[] names = temp.split(regex);
for (String string : names) {
System.out.println("-"+string+"-");
}
}
}
输出结果
12800001111:false
qwe#hsdhk$shjkq
-kh-
-389-
-djsjh-