正则表达式注释匹配java中的代码不能正常工作

时间:2014-01-12 15:50:36

标签: java regex

我有这个代码用于识别注释并在java中打印它们

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Solution {
    public static void main(String[] args) {
        Pattern pattern = Pattern.compile("(\\/\\*((.|\n)*)\\*\\/)|\\/\\/.*");
        String code = "";
        Scanner scan = new Scanner(System.in);
        while(scan.hasNext())
        {
            code+=(scan.nextLine()+"\n");

        }
        Matcher matcher = pattern.matcher(code);
        int nxtBrk=code.indexOf("\n");
        while(matcher.find())
        {

            int i=matcher.start(),j=matcher.end();
            if(nxtBrk<i)
            {
                System.out.print("\n");
            }
            System.out.print(code.substring(i,j));
            nxtBrk = code.indexOf("\n",j);

        }



    scan.close();
    }

}

现在我尝试针对此输入的代码

 /*This is a program to calculate area of a circle after getting the radius as input from the user*/  
\#include<stdio.h>  
int main()  
{ //something

它输出正确而只有评论。但是当我提供输入时

 /*This is a program to calculate area of a circle after getting the radius as input from the user*/  
\#include<stdio.h>  
int main()  
{//ok
}  
/*A test run for the program was carried out and following output was observed  
If 50 is the radius of the circle whose area is to be calculated
The area of the circle is 7857.1429*/  

程序输出整个代码而不仅仅是注释。我不知道添加最后几行有什么不妥。

编辑:解析器不是一个选项,因为我正在解决问题,我必须使用编程语言。链接https://www.hackerrank.com/challenges/ide-identifying-comments

2 个答案:

答案 0 :(得分:3)

使用正则表达式解析源代码非常不可靠。我建议你使用专门的解析器。使用antlr创建一个非常简单。而且,由于您似乎正在解析C源文件,因此可以使用C grammar

答案 1 :(得分:2)

你的模式,它的Java引用(和一些不必要的反斜杠),是这样的:

(/\*((.|
)*)\*/)|//.*

这很好,除了它只有贪婪的量词,这意味着它将匹配从第一个/*最后一个 */。你需要非贪婪的量词来获得这种模式:

(/\*((.|
)*?)\*/)|//.*

因为它现在与*/之后的第一个 /*匹配,所以变化很小,结果很重要。重新编码为Java代码。

Pattern pattern = Pattern.compile("(/\\*((.|\n)*?)\\*/)|//.*");

(请注意,您非常接近与正则表达式匹配的合理范围。实际上,它实际上是不正确的,因为您可能包含/*//的字符串。但是你可能会侥幸逃脱......)