Building a Smart IDE: Identifying comments

  • + 0 comments

    Java 15 solution:

    import java.io.*;
    import java.util.*;
    import java.util.regex.Pattern;
    import java.util.regex.Matcher;
    public class Solution {
        public static void main(String[] args) {
            Scanner scanner = new Scanner(System.in);
            Pattern single_pattern = Pattern.compile("//.*"); // "// +anything"
            Pattern multi_start_pattern = Pattern.compile("/\\*.*"); // "/* +anything"
            Pattern multi_end_pattern = Pattern.compile(".*\\*/"); // "anything+ */"
            Pattern multi_pattern = Pattern.compile("/\\*.*\\*/"); // "/* +anything+ */"
            boolean multi_flag = false; //Flag=true if /* is already found but */ not yet reached. 
            Matcher matcher;
            while(scanner.hasNextLine()){
                String line = scanner.nextLine();
                if (multi_flag)
                {   // If multiple comment already started, 
                    // Print the entire line OR till end of multi-line comment
                    matcher = multi_end_pattern.matcher(line);
                    if (matcher.find())
                    {   multi_flag=false; 
                        System.out.println(matcher.group().trim());
                    }
                    else    System.out.println(line.trim());
                }
                else
                {   // Check for start and end of Multi-line Comment in same line
                    matcher = multi_pattern.matcher(line);
                    if (matcher.find()) System.out.println(matcher.group().trim());
                    else
                    {   //Check for Start of Multi-Line Comment 
                        matcher = multi_start_pattern.matcher(line);
                        if (matcher.find()) 
                        {   multi_flag=true;
                            System.out.println(matcher.group().trim());
                        }
                        else
                        {   // Check for single line comment.  
                            matcher = single_pattern.matcher(line);
                            if (matcher.find()) System.out.println(matcher.group().trim());
                        }
                    }
                }
            }
        }
    }