1. matches() 匹配全部
Pattern p = Pattern.compile("reg");
Matcher m = p.matcher("String");
System.out.println(m.matches());
2:(matches 和find不要一起用,用reset()吐出来)
find()匹配部分
while(m.find()){
SYstem.out.println(m.group());//group() 每次循环 find()匹配到的部分
}
replaceAll() 替代匹配的所有
System.out.println(m.replaceAll("java"));
比replaceAll()更灵活的替换appendReplacement(StringBuffer sb,String yourString);
//把偶数index的java 替换为"猫叔";
StringBuffer sb = new
StringBuffer();
int i=0;
while(m.find()){
i++;
if(i%2==0){
m.appendReplacement(sb, "猫叔");
}
}
m.appendTail(sb);
System.out.println(sb);
3.更强大的分组()()式
/*Pattern p2 =
Pattern.compile("([\\w[-._.]]+)(@[\\w[\\d]]+\\.[\\w]+)");
Matcher m2
=p2.matcher("-newobj_1@163.com,newobj@163.com,1299291758@qq.com");
while(m2.find()){
System.out.println(m2.group(1));
}*/
4.实际应用(爬email)
...所有以上的内容如下:
package first;
import java.io.BufferedReader;
import java.io.File;
import
java.io.FileReader;
import java.io.IOException;
import
java.util.regex.Matcher;
import java.util.regex.Pattern;
public class T1 {
/**
* @param args
*/
public static void main(String[] args)
{
//认识\s:space, \w: [a-zA-Z_0-9] , \d:[0-9]
//System.out.println("
\r\n\t".matches("\\s{4}"));
//System.out.println("hello
sir".matches(".*sir$"));
//System.out.println("newobj@163.com".matches("[\\w[_.]]+@[\\w[_.]]+\\.[\\w[_.]]+"));
/*Pattern
p = Pattern.compile("[\\d]{3,5}");
String tt =
"123-2345-33333-00-12";
Matcher m =
p.matcher(tt);
System.out.println(m.matches());
m.reset();
System.out.println(m.find());
System.out.println(m.find());
System.out.println(m.find());
System.out.println(m.find());*/
//看group(当前匹配的结果)以及repalceAll;
Pattern
p = Pattern.compile("java",Pattern.CASE_INSENSITIVE);
String a = "I lova
java ,he heats Java, hanmeimei love JAva too , and you about java
?";
Matcher m =
p.matcher(a);
// while(m.find()){
// System.out.println(m.group());
// }
//System.out.println(m.replaceAll("java"));
//把偶数index的java
替换为"猫叔";
/*StringBuffer sb = new StringBuffer();
int
i=0;
while(m.find()){
i++;
if(i%2==0){
m.appendReplacement(sb,
"猫叔");
}
}
m.appendTail(sb);
System.out.println(sb);*/
//看看更强大的group
/*Pattern
p2 = Pattern.compile("([\\w[-._.]]+)(@[\\w[\\d]]+\\.[\\w]+)");
Matcher m2
=p2.matcher("-newobj_1@163.com,newobj@163.com,1299291758@qq.com");
while(m2.find()){
System.out.println(m2.group(1));
}*/
//爬email
BufferedReader
bfr = null;
try{
bfr = new BufferedReader(new FileReader(new
File("D:/大家留下email吧.htm")));
String line ="";
String myemail =
"newobj@163.com";
Pattern pemail =
Pattern.compile("[\\w_-]+@[\\w\\d]+\\.[\\w]+");
Matcher meail =
null;
//meail =
pemail.matcher(myemail);
//System.out.println(meail.matches());
while((line=bfr.readLine())!=null){
meail
=
pemail.matcher(line);
while(meail.find()){
System.out.println(meail.group());
}
}
}catch
(Exception e) {
e.printStackTrace();
}finally{
try
{
bfr.close();
} catch (IOException e)
{
e.printStackTrace();
}
}
}
}