Java-使用Regex在字符串线中识别评论



我如何在字符串中识别"注释"?我的"评论"以*

开头

例如,*this is a comment.将被认为是评论。

这是我的代码:

public static boolean isComment(String s) {
    s = s.replaceAll("\s+","");
    String comment = "'*'[a-zA-Z0-9_]+"; //Somehow using *[a-zA-Z0-9_]+ does not work.
    Pattern p = Pattern.compile(comment);
    Matcher m = p.matcher(s);
    if(m.find())
        return true;
    return false;
}

您可以为您的方法使用以下代码:

String s="hey *this is a comment*";
String comment = "\*[^*]*\*"; 
Pattern p = Pattern.compile(comment);
Matcher m = p.matcher(s);
if(m.find())
    System.out.println("found you, bad comment!");
else
    System.out.println("it looks like there is no comment...");

输入:

hey *this is a comment*

输出:

found you, bad comment!

输入:

I am not a comment right?

输出:

it looks like there is no comment...

您可以根据您的确切需求进行调整:

如果评论应在行的开头开始使用:

"^\*[^*]*\*"

如果您不需要关闭*即可将消息识别为注释,请使用:

"\*.*"

作业:

http://www.rexegg.com/regex-quickstart.html

使用此正则 "^\*"字符串而不是"'*'[a-zA-Z0-9_]+"

我希望帮助您

最新更新