Search code examples
javaregexcurly-braces

regex to curly braces on their own or with the 'else' word


I'm trying to to write some custom definitions for the code counting tool cloc, but unfortunately regular expressions are not my strong point.

I'm struggling to write a regex that will match lines containing only whitespace before and/or after { or }

I also need to match lines that contain white space and } followed by the keyword else

i.e. in the following sample:

1  if ( some condition ) {
2     do something
3  } else if ( some other condition ) {
4     do this
5  } else {
6     do this
7  }
8  
9  if ( some other condition ) 
10 {
11   do this
12 }

I need a regex that would match lines 5, 7, 10 and 12.

I started with a very simple \s*{ but this matches against lines that contains words as well.


Solution

  • This regex follows your outlined specifications:

    String regex = "\\s*[{}]\\s*|\\s*\\}\\s*else.*";
    

    It matches lines containing either:

    • 0 or more spaces, followed by { or }, followed by 0 or more spaces

      or

    • 0 or more spaces, followed by a }, then 0 or more spaces, then else, then anything.