Search code examples
javaregexcompiler-construction

regex - Java starts with * and ends with a newline (\n)


Basically this is what it looks like:

int abc = 10;
* this is a comment

so, I just want to find the * this is a comment so that I can remove it from the string. I have tried some examples although it doesn't seem to work. The idea is basically starts with * followed by any combination of words, numbers, or symbols (anything really) that ends with a newline (\n).


Thank you.


Solution

  • The pattern ^\*.*$ should work here:

    String line = "Not a comment\n* This is a comment\n*This is also a comment\n";
    line += "Not a * comment.";
    String pattern = "^\\*.*$";
    
    Pattern r = Pattern.compile(pattern, Pattern.MULTILINE);
    Matcher m = r.matcher(line);
    
    while (m.find( )) {
        System.out.println("Found value: " + m.group(0) );
    }
    
    Found value: * This is a comment
    Found value: *This is also a comment
    

    Not much to explain here, except that * is a regex metacharacter, and if you want to use it as a literal, then it needs to be escaped by a backslash.

    Demo