简体   繁体   中英

Regular expression for single line java comments

I am new to regular expression, Am finding empty IF statements by using this if[\\\\s]*\\\\([^\\\\)]*\\\\)[\\\\s]*\\\\{((/\\\\*(.|[\\\\r\\\\n])*?\\\\*/)|\\\\s)*\\\\} and its works fine fine multi line comments with empty statements but not find single line comments. It find the below scenarios

if (true) {

        /*
         * fsdsddgd ddgdgdfg gdfgdgdfg gdfgdfg fgdfgfg
         */

        /*
         * fsdsddgd ddgdgdfg gdfgdgdfg gdfgdfg fgdfgfg
         */
    }

if (true) {


    }

Not find the below scenarios

if (true) {
        // kavi
        // kamal
        // kamal
    }

    if (true) {
        // kavi
    }

please give me valuable solutions for this.

Not A Great Idea, but if you have to...

As you can see in the comments I'm not terribly fond of the idea, but since you asked for it, this will work with your input (see demo ):

if\s*\([^\{]*\{(?:[ \t]*//.*)?[ \t]*(?:[\r\n]*[ \t]*(?://.*)?)*[\r\n]*[ \t]*(?://.*)?}
  • The if\\s*\\([^\\{]*\\{ gets us to the opening brace
  • The (?:[ \\t]*//.*)?[ \\t]* gets us to the end of the line, matching an optional comment along the way
  • The (?:[\\r\\n]*[ \\t]*(?://.*)?)* matches a series of lines with optional comments
  • The [\\r\\n]*[ \\t]*(?://.*)?} gets us to the final brace.

Tokens need to be properly escaped, so try this code:

List<String> matchList = new ArrayList<String>();
try {
    Pattern regex = Pattern.compile("if\\s*\\([^\\{]*\\{(?:[ \t]*//.*)?[ \t]*(?:[\r\n]*[ \t]*(?://.*)?)*[\r\n]*[ \t]*(?://.*)?}");
    Matcher regexMatcher = regex.matcher(subjectString);
    while (regexMatcher.find()) {
        matchList.add(regexMatcher.group());
    } 
} catch (PatternSyntaxException ex) {
    // Syntax error in the regular expression
}

else if

In the comments you say you may not want else if

In that case, use this:

(?<!else )if\s*\([^\{]*\{(?:[ \t]*//.*)?[ \t]*(?:[\r\n]*[ \t]*(?://.*)?)*[\r\n]*[ \t]*(?://.*)?

In code:

List<String> matchList = new ArrayList<String>();
try {
    Pattern regex = Pattern.compile("(?<!else )if\\s*\\([^\\{]*\\{(?:[ \t]*//.*)?[ \t]*(?:[\r\n]*[ \t]*(?://.*)?)*[\r\n]*[ \t]*(?://.*)?");
    Matcher regexMatcher = regex.matcher(subjectString);
    while (regexMatcher.find()) {
        matchList.add(regexMatcher.group());
    } 
} catch (PatternSyntaxException ex) {
    // Syntax error in the regular expression
}

Let me know if you have questions!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM