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


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值