要检测一个java文件有多少行是注释行,我分了两种情况一种是直接以"//"开头的,则可以用 matches("//.*")另一种是以"/*"开头,以"*/"结尾的, 那matches()要怎么设置呢matches("/*.*") 和 matches("*.*/") 这样对么,后面的编译器提升有问题Java正则表达式注释

解决方案 »

  1.   

    正则处理这个问题比较有难度,例如
    String str = "/*comment // continue*/"; /* go to */ // What's this
    这样的情况用正则怎么处理?
      

  2.   

    因为本身/是转义字符,所以需要////才可以。。
    第二个如果提取的话,
    可以用Pattern p=Pattern.compile("(?s)/*(.*?)/*");
    总行数num
    如果只是统计行数的话,检测到/*设置的计数值i开始计数,遇到*/计数结束,然后总行数num+=i,i归0;
    继续运行。。
    当然。这中间如果出现一行多个/*的情况无法处理,但是这属于异常情况。可以不用考虑
      

  3.   

    匹配条件compile("(?s)/*(.*?)/*")
    //忽略换行(?s)
    //匹配/*开头的,
    //(.*?)通配
    //匹配*/结尾的。
      

  4.   

    嗯。我式子填错了String str="hte/*feggewg*/ht";
    Pattern p=Pattern.compile("(?s)//*(.*?)/*/");

    Matcher m=p.matcher(str);
    while(m.find()){
    System.out.println(m.group(0));
    }
    结果:/*feggewg*/
    *是通配字符,需要转义
      

  5.   

    写了个,测试基本能过,不过最好是作为参考,然后再复杂的情况下测试一下
    import java.util.regex.Matcher;
    import java.util.regex.Pattern;public class Hello {
        public static void main(String[] args) {
            String str = "\"String\\\" text;\" biao /* // \"goto\" */ \"//hello /*comment*/\"// What's this.";        String doubleQuote = "(\".+?[^\\\\]\")"; // 需要再处理"string\""的情况
            String lineComment = "(//.+$)";
            String blockComment = "(/\\*.+?\\*/)";
            Pattern pattern = Pattern.compile(doubleQuote + "|" + lineComment + "|" + blockComment);
            Matcher matcher = pattern.matcher(str);        while (matcher.find()) {
                String matchedString = matcher.group(0);
                if (!matchedString.startsWith("\"")) {
                    System.out.println(matchedString);
                }
            }
        }
    }
      

  6.   

    输出
    /* // "goto" */
    // What's this.