I have this code for Identifying the comments and print them in 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();
}
}
Now when I try the code against this input
/*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
It outputs right and only the comments. But when I give the input
/*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*/
The program outputs the whole code instead of just the comments. I don't know what wrong is doing the addition of that last lines.
EDIT: parser is not an option because I am solving problems and I have to use programming language . link https://www.hackerrank.com/challenges/ide-identifying-comments
"/* A string, not a comment */","http://foo","/path/*.txt" /* A file path */. You need to recognize all tokens that can contain comment boundaries to recognize comment boundaries correctly.Pattern.compile("(?:" + COMMENT_REGEX + ")|(?:" + STRING_REGEX + ")", ...)whereSTRING_REGEX = "\"(?:[^\"\\\\]|\\\\.)*\"|'(?:[^'\\\\]|\\\\.)*'". That way, quotes will match as string tokens which will effectively hide any apparent comment boundaries inside string tokens.