import java.util.Arrays;
import java.util.Comparator;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
class MyComparator implements Comparator<String>{
public int compare(String ip1, String ip2) {
Pattern p = Pattern.compile("\\d{1,3}");
Matcher m1 = p.matcher(ip1);
Matcher m2 = p.matcher(ip2);
while(m1.find()){
m2.find();
System.out.println(m1.group() + " " + m2.group());
int i1 = Integer.valueOf(m1.group());
int i2 = Integer.valueOf(m2.group());
if(i1 < i2) return -1;
else if(i1 > i2) return 1;
}
return 0;
}
}
public class RegexDemo {
/**
* @param args
*/
public static void main(String[] args) {
/*
* 治疗口吃:"我我..我我....我我要要...要要..要要要要学学学...学学学学编编编...编编编编程程程..程..程程...程.程程"
* 变成“我要学编程”
* 1.替换 2.处理叠词
*/
String str="我我..我我....我我要要...要要..要要要要学学学...学学学学编编编...编编编编程程程..程..程程...程.程程";
str = str.replaceAll("\\.+", "");
str = str.replaceAll("(.)\\1+", "$1");
System.out.println(str);
/*
* ip地址的排序:
* 192.168.10.34 127.0.0.1 3.3.3。3 105.70.11.55
* 对应段的数字比较!
*
*/
//第一种方法,获取每一个字段的数字,数字之间进行比较
String[] ip = {"192.168.10.34", "127.0.0.1", "3.3.3.3", "105.70.11.55"};
Arrays.sort(ip, new MyComparator());
for(int i=0; i<ip.length; ++i)
System.out.println(ip[i]);
//第二种方法,将每一个字段的长度都变成3位
String[] ip2 = {"192.168.10.34", "127.0.0.1", "3.3.3.3", "105.70.11.55"};
for(int i=0; i<ip2.length; ++i){
ip2[i] = ip2[i].replaceAll("(\\d+)", "00$1");//首先每一段都加上连个前导0
ip2[i] = ip2[i].replaceAll("0*(\\d{3})", "$1");//将每一段变成标准的3位
}
Arrays.sort(ip2);
for(int i=0; i<ip2.length; ++i){
ip2[i] = ip2[i].replaceAll("0*(\\d+)", "$1");//将每一段的数字还原!
System.out.println(ip2[i]);
}
/*
* 对邮件地址校验!
*/
String mail = "abc@sina.com.cn";
boolean bf = mail.matches("\\w+@\\w+(\\.\\w+)+");
System.out.println(mail + ":" + bf);
String sr=" fsdfs.12345 ";
Pattern p = Pattern.compile("\\w+");
Matcher m = p.matcher(sr);
while(m.find()){
System.out.println(m.group());
}
/*
* 正则表达是实现ip地址的检验功能!
*/
String ip3 = null;
String ipRegex = "^(\\d|[1-9]\\d|1\\d*|2[0-4]\\d|25[0-5])(\\.\\1){3}$";
/*
* \\d|[1-9]\\d|1\\d*|2[0-4]\\d|25[0-5]
* 该段的数字只有一位的时候,两位数字的时候,三位数字的时候(1开头的和2开头的)
*/
Scanner scan = new Scanner(System.in);
while((ip3 = scan.nextLine()) != null){
if(ip3.matches(ipRegex)) System.out.println("True");
else System.out.println("false");
}
}
}