简体   繁体   中英

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

ie 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.

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.

以下正则表达式将匹配由以下更多实例组成的行: whitespaces{}else单词组件,但没有别的:

^(?:[\s{}]|else)+$

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