JAVA使用正则表达式

主要是搞清楚matches()/lookingAt ()/find()这三个方法的区别,以及会使用replaceAll() replaceFirst() appendReplacement()  appendTail() ,请看代码

 

 

package test;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class RegTest {
	public static void main(String[] args)
	{
		Pattern reg = Pattern.compile("(20\\d{2})-([01]\\d)-([0-3]\\d)");
		Matcher matcher = null;
		System.out.println(reg.pattern());
		matcher = reg.matcher("2012-02-25");
		
		//matches()方法尝试对整个目标字符展开匹配检测,是只有整个目标字符串完全匹配时才返回真值
		if (matcher.matches())
		{
			System.out.println("time:"+matcher.group(0));
			System.out.println("year:"+matcher.group(1));
			System.out.println("year:"+matcher.group(2));
			System.out.println("year:"+matcher.group(3));
		}
		
		Pattern reg2 = Pattern.compile("\\d*");
		System.out.println(reg2.pattern());
		matcher = reg2.matcher("2012abcd");
		
		//lookingAt()方法将检测目标字符串是否以匹配的子串起始
		if (matcher.lookingAt())
		{
			System.out.println("num:"+matcher.group());
		}
		
		Pattern reg3 = Pattern.compile("\\d+");
		System.out.println(reg3.pattern());
		matcher = reg3.matcher("asf2012abcd2011jdf2010jk");
		
		//find()方法尝试在目标字符串里查找下一个匹配子串
		while(matcher.find())
		{
			System.out.println("matcherStr:"+matcher.group());
		}
		
		//appendReplacement() 将当前匹配子串替换为指定字符串,并且将替换后的子串以及其之前到上次匹配子串之后的字符串段添加到一个StringBuffer对象里
		Pattern reg4 = Pattern.compile("(hello|goodbye)");
		matcher = reg4.matcher("sayhelloandsaygoodbyeandsayhelloandsaysomething");
		StringBuffer sb = new StringBuffer();
		
		while (matcher.find()){
			System.out.println("matcherStr:"+matcher.group());
			matcher.appendReplacement(sb, "IT");
			System.out.println("sb:"+sb);
		}
		//appendTail() 方法则将最后一次匹配工作后剩余的字符串添加到一个StringBuffer对象里
		//可以在一次或多次调用 appendReplacement 方法后调用它来复制剩余的输入序列
		matcher.appendTail(sb);
		System.out.println("sb:"+sb);
	}
}


输出结果如下:

(20\d{2})-([01]\d)-([0-3]\d)
time:2012-02-25
year:2012
year:02
year:25
\d*
num:2012
\d+
matcherStr:2012
matcherStr:2011
matcherStr:2010
matcherStr:hello
sb:sayIT
matcherStr:goodbye
sb:sayITandsayIT
matcherStr:hello
sb:sayITandsayITandsayIT
sb:sayITandsayITandsayITandsaysomething


 

你可能感兴趣的:(java,工作,String,正则表达式,Class,2010)