在 "10 println "Testing if then" //Test Comment 行中查找评论的正则表达式是什么

What can be the regex to find comments in line "10 println "Testing if then" //Test Comment

对于行,

10  println "Testing Comment" //Test Comment

可以使用什么正则表达式来查找整个字符串的“//测试评论”。我想将其用于标记化,因为我正在 java.

中创建词法分析器

代码:

StringBuilder sb = new StringBuilder();
    String[] p = new String[5];
    p[0] = "(?<Reserved>\bPRINTLN\b)"; //RESERVED WORDS 
    p[1] = "(?<Comments> //.*)";
    p[2] = "(?<Constants>[0-9]+)"; //Constants eg: 21 54 14215
    p[3] = "(?<Special>[\[\]/.$*\-+=><#()%,!|&{}])"; //SPECIAL CHAR Eg:-+*/ etc
    p[4] = "(?<Identifiers>\w+)"; //Identifiers eg: circum radius


    for (String s: p) {
        sb.append(String.format("|(%s)", s)); 
    } //for ends here

    Pattern tp = Pattern.compile(new String(sb.substring(1))); // adding the patterns one after another separated by |

    Matcher m = tp.matcher(line);

我试过使用 //.* 但它与注释不匹配。 使用匹配器中的查找方法,我基于命名的捕获组进行标记。

你可以试试this regex:

\/\/.*
  • \/\/ 匹配 // 开始评论
  • .* 匹配 // 之后的任意数量的字符,行终止符除外

您的问题一定是您使用了 // 而不是 \/\// 是元字符,已用反斜杠转义。下次我建议你在询问之前使用regex101,简单的错误将被突出显示,你可以快速测试它。

试试这个:

(?=\/\/)[\s\S]+

演示:https://regex101.com/r/1IESlB/1