Removing an empty line with .replaceAll and regex in Java -
pardon if answered already. have hunted 2 days answer , got far. here problem solve:
write method called stripcomments accepts scanner representing input file containing java program parameter, reads file, , prints file's text comments removed. comment text on line // end of line, , text between /* , */ characters. example, consider following text:
import java.util.*; /* program suzy student */ public class program { public static void main(string[] args) { system.out.println("hello, world!"); // println } public static /* hello there */ void foo() { system.out.println("goodbye!"); // comment here } /* */ }
this came with:
public static void stripcomments(scanner scan) { while(scan.hasnextline()) { string str1 = scan.nextline(); string str2 = str1.replaceall("(/(\\*).*?(\\*)/)|(//.*?$)|(/(\\*).*?$)|([a-za-z\\s0-9]*?\\*(/))", ""); system.out.println(str2); } }
this result:
import java.util.*; public class program { public static void main(string[] args) { system.out.println("hello, world!"); } public static void foo() { system.out.println("goodbye!"); } }
while of correct, don't know how rid of line above "public class program {." how rid of line , there better way write regex expression?
thank in advance!
i came second replace command
str = str.replaceall("\n\\s*\n", "\n");
this requires pass in entire file though, wouldn't work line line.
if want continue going line line, should
if(str2.matches("\\s*")) continue;
p.s. last grouping of parenthesis around regex unnecessary if don't have quantifier. , multiline comment won't work 3+ lines, such as:
/* * * multiline * comment */
since passing in line line.
Comments
Post a Comment