您的位置:首页 > 其它

正则表达式(Regex)--(2)

2014-07-08 22:12 176 查看
/*
* 1,治口吃。
*/
public static void test_1(){
String str = "我我...我我...我我我要...要要要要...要要要要..学学学学学...学学编编...编编编编..编..程程...程程...程程程";
//1,将字符串中.去掉。 用替换。
str = str.replaceAll("\\.+", "");
System.out.println(str);
//2,替换叠词。
str = str.replaceAll("(.)\\1+", "$1");
System.out.println(str);
//我要学编程
}

//2,对邮件地址校验。
public static void test_3() {
String mail = "abc1@sina.com.cn";
String regex = "[a-zA-Z0-9_]+@[a-zA-Z0-9]+(\\.[a-zA-Z]{1,3})+";
//regex = "\\w+@\\w+(\\.\\w+)+";
boolean b = mail.matches(regex);
System.out.println(mail+":"+b);
}

/*
3,网页爬虫:获取网页中的邮箱
*/
public static List getMailsByWeb() throws IOException {
//1,读取源文件。
URL url = new URL("http://192.168.1.100:8080/myweb/mail.html");
BufferedReader bufIn = new BufferedReader(new InputStreamReader(url.openStream()));
//2,对读取的数据进行规则的匹配。从中获取符合规则的数据.
String mail_regex = "\\w+@\\w+(\\.\\w+)+";
List list = new ArrayList();
Pattern p = Pattern.compile(mail_regex);
String line = null;
while((line=bufIn.readLine())!=null){
Matcher m = p.matcher(line);
while(m.find()){
//3,将符合规则的数据存储到集合中。
list.add(m.group());
}
}
return list;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: