I\'d like to do a function which gets a string and in case it has inline comments it removes it.
public class sample {
public static void main(String[] arg
Try
replaceAll("(?s)/\\*.*?\\*/", "")
Example:
String code = "/**THIS IS SAMPLE CODE */ public class TestFormatter{public static void main(String[] args){int i =2; String s= \"name\";\\\\u give give change the values System.out.println(\"Hello World\");//sample}}";
System.out.println(code.replaceAll("(?s)/\\*.*?\\*/", ""));
Output:
public class TestFormatter{public static void main(String[] args){int i =2; String s= "name";\\u give give change the values System.out.println("Hello World");//sample}}
PS.
if you also want to remove last comments //sample}}
Then use split()
System.out.println(code.replaceAll("(?s)/\\*.*?\\*/", "").split("//")[0]);
// keep in Mind it will also Remove }} from //sample}}
Output:
public class TestFormatter{public static void main(String[] args){int i =2; String s= "name";\u give give change the values System.out.println("Hello World");
replaceAll("((/\\*)[^/]+(\\*/))|(//.*)", "")
This will remove single line, multi-line or doc comments.
The JavaScript compatible regex is ((/\*)[^/]+(\*/))|(//.*)
, which you can try with regexpal.com.