java正则表达式小结

javaAPI:

 

public static void main(String[] args) {
        String str = "lixin_2002@163.com";
        String reg = "([a-zA-Z0-9]+)\\@[a-zA-Z0-9]+\\.[a-zA-Z0-9]+$";
        Pattern p = Pattern.compile(reg); 
        Matcher m = p.matcher(str);
        System.out.println(m.find());
        
}

 

 jakarta-oro的使用1(简单匹配):

 

 

    public static void main(String[] args) throws MalformedPatternException {
	//取出日志文件的IP和时间
        String log = "172.26.155.241 - - [26/Feb/2001:10:56:03 -0500]";
        String logreg = "(\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3})\\s-\\s-\\s\\[([^\\]]+)\\]";
        PatternCompiler pc = new Perl5Compiler();
        org.apache.oro.text.regex.Pattern p = pc.compile(logreg);
        PatternMatcher pm = new Perl5Matcher();
        System.out.println(pm.contains(str,p));
        if(pm.contains(log,p)){
            org.apache.oro.text.regex.MatchResult mr = pm.getMatch();
            System.out.println("ip: " + mr.group(1));
            System.out.println("time: " + mr.group(2));
        }
    }

  jakarta-oro的使用2(匹配多个):

 

	public static void main(String[] args) throws MalformedPatternException {
		//取出HTML标签里的属性值及值  分两次
		String html = "<font face='Arial, Serif' size='12' color='red'>";
		String reg1 = "<[a-z]+\\s+(.+)>";
		String reg2 = "([a-z]+)='([^']+)'";
		PatternCompiler compiler = new Perl5Compiler();
		Pattern pattern = compiler.compile(reg1);
		PatternMatcher matcher = new Perl5Matcher();
		System.out.println(matcher.contains(html, pattern));
		if(matcher.contains(html, pattern)){
			MatchResult result = matcher.getMatch();
			String arrs = result.group(1); //先取出属性列表
			System.out.println(arrs);
			Pattern pattern2 = compiler.compile(reg2);
			PatternMatcherInput input = new PatternMatcherInput(arrs);
			while(matcher.contains(input, pattern2)){
				result = matcher.getMatch();
				System.out.println(result.group(1)+"=" + result.group(2));
			}
		}
	}

   jakarta-oro的使用3(字符串替换):

	public static void main(String[] args) throws MalformedPatternException {
		//将str1和str2 的前面aaa部分替换成www 而后面的不替换
		String str = "aaa&abc";
		String str2 = "aaa&cde";
		String reg = "aaa&(.+)";
		PatternCompiler compiler = new Perl5Compiler();
		Pattern pattern = compiler.compile(reg,Perl5Compiler.CASE_INSENSITIVE_MASK);
		PatternMatcher matcher = new Perl5Matcher();
		String result = Util.substitute(matcher, pattern, 
				new Perl5Substitution("www&$1"), //注意:$1 $2等 表示已经匹配且提取出来的组
				str,Util.SUBSTITUTE_ALL);
		System.out.println(result);
	}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值