正则表达式的简单应用

  很多的工具,如eclipse,ue等在查找,替换时也都是支持正则表达式的。下面是一些例子:

  eclipse中去掉/* */:       /\*(.|[\r\n])*?\*/全部替换为空即可
  eclipse中去掉//:           //.*$全部替换为空即可
  eclipse中去掉import :    import.*$全部替换为空即可
  eclipse中去掉空行:       ^\s*\n全部替换为空即可
  ue中去掉空行               %[ ^t]++^p

 

  将最内层括号中的内容替换为"abc"的Java代码例子:

String s = "onu 1/1/1(def (ghj(\"test string\")jkl))";
        System.out.println(s.replaceAll("(.*\\()([^\\)]*)(.*)", "$1\"abc\")$3"));

        //  (.*\\()  匹配至最内层的左括号--[onu 1/1/1(def (ghj(],Java默认的匹配是贪婪匹配
        //  ([^\\)]*) 匹配最内层括号中的内容 --["test string"]
        //   (.*)  匹配最内层右括号之后的内容--[)jkl))]
        Pattern p = Pattern.compile("(.*\\()([^\\)]*)(.*)");
        Matcher m = p.matcher(s);

        while(m.find()){
            for(int i=0;i<= m.groupCount();i++){
                System.out.print("[" + m.group(i) + "]");
            }
            System.out.println("");
        }

  

  从日志文件中提取IP地址及时间的Java代码例子:

String testStr = "172.26.155.241 - - [26/Feb/2011:10:53:06 -0500] \"GET IsAlive.html HTTP/1.0\" 200 15";
        //   (\\[[^\\]]*\\])") 用户获取[]所包含的时间信息,也可以简单地写成(\\[.*\\])")
        p = Pattern.compile("(\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}).*(\\[[^\\]]*\\])");
        m = p.matcher(testStr);

        while(m.find()){
            for(int i=0;i<= m.groupCount();i++){
                System.out.print("[" + m.group(i) + "]");
            }
            System.out.println("");
        }
        
        String str = "nfa not";
        p = Pattern.compile("(nfa|nfa not)");
        m = p.matcher(str);

        while(m.find()){
            for(int i=0;i<= m.groupCount();i++){
                System.out.print("[" + m.group(i) + "]");
            }
            System.out.println("");
        }

 

posted on 2015-09-20 12:27  lnlvinso  阅读(485)  评论(0编辑  收藏  举报