package zhangweicong.regexDemo;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import java.util.LinkedHashSet;
import java.util.Set;
import java.util.TreeSet;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* 有关正则表达式的一些简单操作
* @author weicong
*
*/
public class RegexDemo {
/**
* @param args
* @throws FileNotFoundException
*/
public static void main(String[] args) throws FileNotFoundException {
/**
* 提取句子中的单词
*/
println("------Demo1----");
String string="Java bow has regular expressions.";
String regex="\\b\\w+\\b";
Pattern pattern=Pattern.compile(regex);
Matcher matcher = pattern.matcher(string);
while(matcher.find()){
System.out.println(matcher.group());
}
/**
* 提取句子
* */
println("------Demo2----");
String s2="我我我我我我...要要要要要.........要要要要...要学学......编编编编编编...程";
s2=s2.replaceAll("\\.+", "");
s2=s2.replaceAll("(.)\\1+","$1");
println(s2.toString());
/*//非正则方法
Set set = new LinkedHashSet();
for(char ch : s2.toCharArray()){
set.add(ch);
}
for( Object obj : set.toArray()){
System.out.print(obj.toString().replaceAll("\\.", ""));
}
println("");*/
/**
* 对IP地址排序
*/
println("---Demo3---");
String ip="1.1.1.1 2.34.4.67 192.24.127.0 198.198.2.3";
ip=ip.replaceAll("(\\d+)","00$1");
println(ip);
ip=ip.replaceAll("0*(\\d{3})","$1");
println(ip);
TreeSet<String> tree=new TreeSet<String>();
for(String s : ip.split(" ")){
tree.add(s);
}
for(String s : tree){
println(s.replaceAll("0*(\\d+)", "$1"));
}
/**
* 邮件地址校验
*/
println("---Demo4---");
String mail="zhangweicong4@sina.com.cn";
String regMail="\\w+@\\w+(\\.[a-zA-Z]+)+";
println(mail.matches(regMail));
/**
* 检索文件中的邮件地址
*/
println("---Demo5---");
Reader reader=new FileReader("mail.txt");
getMailAddress(reader);
}
/**
*
* 按行读取字符流中的邮件地址
* 文件内容
* zhangweicong@111.com.cn dfgsdfjkhgjkdfs
fdgadfsgsdf
zhangweicodfsgdfng@1dfsgh11gdfsg;com.cn
zhangweicong@111.com.cndfsgdf... dsghdf<html>
zhangweicong@211.com.cn;''dsfighufig
zhangweicong@sina.com.cnzhangweicong@sina.com.cn dsgdfsdffc
zhangweicong2@sina.com.cn dsfgsdfsdfgdfg dser45ts esgh dsgsfs@sdfgs dfgs
zhangweicong3@sina.com.cndgs
zhangweicon4g@sina.com.cn
zhangweicong5@111.com.cn
*/
public static void getMailAddress(Reader reader){
String regMail="\\w+@\\w+(\\.[a-zA-Z]+)+";
BufferedReader bufr=new BufferedReader(reader);
Matcher matcher=null;
String line=null;
try {
while((line=bufr.readLine())!=null){
//System.out.println(line);
matcher=Pattern.compile(regMail).matcher(line);
while(matcher.find()){
System.out.println(matcher.group());
}
}
} catch (IOException e) {
e.printStackTrace();
}
try {
reader.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void println(Object string){
System.out.println(string.toString());
}
}
黑马程序员--正则表达式--基本示例
最新推荐文章于 2018-11-25 18:57:04 发布