您的位置:首页 > 其它

正则表达式1

2014-12-29 14:27 197 查看
import java.util.Iterator;
import java.util.TreeSet;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class RegexDemo {

public static void main(String[] args) {
method_8();
}

/*
* 需求:定义一个功能对QQ号进行校验。 要求:长度5~15. 只能是数字, 0不能开头
*/
public static void method_1() {
String qq = "101885";
String regex = "[1-9]\\d{4,14}";
System.out.println(qq + ":" + qq.matches(regex));
}

/*
* 需求:手机号码验证
*/
public static void method_2() {
String tel = "18190029004";
String regex = "1[358]\\d{9}";
System.out.println(tel + ":" + tel.matches(regex));
}

/*
* 需求:叠词切割
*/
public static void method_3() {
String str = "akjdhkahjjauuuuqjhadwww;k";
String regex = "(.)\\1+";
String[] arr = str.split(regex);
for (String s : arr) {
System.out.println(s);
}
}

/*
* 需求:替换 1.手机号部分替换 2.叠词替换
*/
public static void method_4() {
String tel = "13840056789";
String regex = "(\\d{3})(\\d{4})(\\d{4})";
System.out.println(tel.replaceAll(regex, "$1****$3"));

String str = "akjdhkahjjauuuuqjhadwww;k";
String reg = "(.)\\1+";
System.out.println(str.replaceAll(reg, "*"));
}

/*
* 需求:获取 三个字母的单词
*/
public static void method_5() {
String str = "ajkdh iqw iqiw qii,wip aido q qw";
String regex = "\\b[a-z]{3}\\b";
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(str);
while (m.find()) {
System.out.println(m.group());
System.out.println(m.start() + " " + m.end());
}
}
/*
* 热热热.热播..播播..播播播.播电电..电影影电电电.电电.视视视..剧
* 热播电影电视剧
*/

public static void method_6(){
String str = "热热热.热播..播播..播播播.播电电..电影影电电电.电电.视视视..剧";
String regex = "\\.+";
String str1 = str.replaceAll(regex, "");
String regex1= "(.)\\1+";
System.out.println(str1.replaceAll(regex1, "$1"));
}

/*
* 对IP地址排序
*
*/

public static void method_7(){
String str = "192.168.2.3   8.8.8.8 127.0.0.1 10.10.10.1";
//加0
String regex = "(\\d+)";
str = str.replaceAll(regex, "00$1");
//去0
String reg = "0+(\\d{3})";
str = str.replaceAll(reg, "$1");
//排序;
TreeSet ts = new TreeSet();
String[] arr = str.split(" +");
for(String s:arr){
ts.add(s);
}
//格式化输出
for(Iterator it = ts.iterator();it.hasNext();){
String ip = (String) it.next();
String re = "0+(\\d{1,3})";
ip = ip.replaceAll(re, "$1");
System.out.println(ip);
}
}
/*
* Email 验证
*
*/
public static void method_8(){
String str = "a@163.com";
String regex = "[a-zA-Z\\d_]+@[a-zA-Z\\d_]+\\.[a-zA-Z]{2,3}";
System.out.println(str.matches(regex));
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: