We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
importjava.io.*;importjava.util.*;importjava.util.regex.Pattern;importjava.util.regex.Matcher;publicclassSolution{publicstaticvoidmain(String[]args){Scannerscanner=newScanner(System.in);Patternsingle_pattern=Pattern.compile("//.*");// "// +anything"Patternmulti_start_pattern=Pattern.compile("/\\*.*");// "/* +anything"Patternmulti_end_pattern=Pattern.compile(".*\\*/");// "anything+ */"Patternmulti_pattern=Pattern.compile("/\\*.*\\*/");// "/* +anything+ */"booleanmulti_flag=false;//Flag=true if /* is already found but */ not yet reached. Matchermatcher;while(scanner.hasNextLine()){Stringline=scanner.nextLine();if(multi_flag){// If multiple comment already started, // Print the entire line OR till end of multi-line commentmatcher=multi_end_pattern.matcher(line);if(matcher.find()){multi_flag=false;System.out.println(matcher.group().trim());}elseSystem.out.println(line.trim());}else{// Check for start and end of Multi-line Comment in same linematcher=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());}}}}}}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Building a Smart IDE: Identifying comments
You are viewing a single comment's thread. Return to all comments →
Java 15 solution: