zoukankan      html  css  js  c++  java
  • Java 正则表达式 Pattern & Matcher

      通常会有这种需求: 在文档中搜索有规律的字符串,然后进行统计或者替换。Java.util.regex包下的Pattern和Matcher这两个类提供了通过正则表达式来匹配查询,甚至替换的功能。那么我们接下来就举个栗子吧 : 

    栗子1:查找文件中以img_数字.png格式的字符串,并在前面添加路径: /test/img/ 

    package test;
    
    import java.io.File;
    import java.util.regex.Matcher;
    import java.util.regex.Pattern;
    import org.apache.commons.io.FileUtils;
    
    public class PatternTest {
    
    	private static final String CONSTSTRING = "<a><img src='img_01.png'/></a>";
    	public static void main(String[] args) throws Exception {
    		File file = new File("C:\Users\Admin\Desktop\test.txt");
    		FileUtils.writeStringToFile(file, CONSTSTRING);
    		String str = FileUtils.readFileToString(file, "UTF-8");
    		StringBuffer stringBuffer = new StringBuffer();
    		//设置Pattern的正则表达式
    		Pattern p = Pattern.compile("img_[0-9]+\u002png");
    		//按规则匹配
    		Matcher m = p.matcher(str);
    		while(m.find()){
    			//将匹配到并替换后的字符串以及前面的字符串添加到StringBuffer中
    			m.appendReplacement(stringBuffer, "/test/img/"+m.group());
    			System.out.println(stringBuffer.toString());
    			System.out.println();
    		}
    		//将匹配到的字符串之后的字符串添加到StringBuffer中
    		m.appendTail(stringBuffer);
    		FileUtils.writeStringToFile(file, stringBuffer.toString(), "UTF-8");
    	}
    }
    

      其实这个问题有个简单方法,这里扩展一下 : 

    package test;
    
    import java.io.File;
    import java.util.regex.Matcher;
    import java.util.regex.Pattern;
    import org.apache.commons.io.FileUtils;
    
    public class PatternTest {
    
        private static final String CONSTSTRING = "<a><img src='img_01.png'/></a>";
        public static void main(String[] args) throws Exception {
            File file = new File("C:\Users\JD07201\Desktop\test.txt");
            FileUtils.writeStringToFile(file, CONSTSTRING);
            String str = FileUtils.readFileToString(file, "UTF-8");
            str = str.replace("img_", "/test/img/"+"img_");
            FileUtils.writeStringToFile(file, str, "UTF-8");
        }
    }
    

      这个方法的前提是匹配条件必须只能映射到目标字符串,在这里就是指匹配条件"img_"必须等价于 "img_[0-9]+\u002png",否则就有可能将不符合条件的字符串也给替换了。

      

  • 相关阅读:
    SNMP监控一些常用OID表的总结
    微信公众号开发(三)----服务号客服消息
    微信公众号开发(二)---验证服务与回复消息
    微信公众号开发(一)-----准备工作
    leveldb文章列表
    TinyIM流程之删除好友
    TinyIM流程之添加好友
    《软件创富----共享软件创业之道》读后感
    TinyIM流程之用户注销
    TinyIM流程之用户退出登录
  • 原文地址:https://www.cnblogs.com/djoel/p/5645846.html
Copyright © 2011-2022 走看看