Regex pattern for matching Case Case statements
We need to identify and then process switch / case statements in code based on some business rules.
Typical switch statement:
switch (a)
{
case "A":
case "B":
result = "T";
result1 = "F";
default: result = "F";
}
I was able to create two patterns to match the radio button body in the first step and the labels and body in the second step, however I am looking for one regex that will allow me to extract the labels and bodies.
We have no nested switches.
Yours faithfully,
a source to share
Since switch statements can be nested, traditional regexes can't handle them (heck, even the fact that it {}
can be nested breaks them). Regular expressions can only handle Regular the Languages . To parse languages that are not regular, you need a parser form. Depending on what language you have (it looks like C, but so much), there might already be a parser you can use (like Sparse for C).
a source to share
Here's where to start, but it's far from ideal - the expression doesn't recognize default values and the end of a switch statement (and possibly includes some other errors).
(?sn:(case (?<label>[^:]+):[ \r\n\t]*)+(?<body>((?!case).)*))
UPDATE
It will also fail if the body contains case
as part of a string or id.
a source to share
Ches. Owens is right in his comments. But for simple cases, you can use the following regex:
switch\s*\((?<expression>[^\)]+)\)\s*\{\s*((default(?<case>)|case\s*(?<case>"[^"]*"|'[^']*'|\w+))\s*:\s*(?<body>((?!\s*(case\b|default\b|\}))("[^"]*"|'[^']*'|[^\}]))*)\s*)+\}
To use it, the regex engine you are using must support explicit multiple named captures and perspectives (like the .NET regex engine). Note that all groups, except the named groups, can be made non-capturing, but to make the regex easier to understand, I did not add "?:" To the group to make them non-capturing groups.
Then you get one match for each operator recognized switch
with the following captures:
-
expression: expression used for the switch (1 capture)
-
: case label or empty (but successful capture) for standard
-
body: body body, one for each case
case and body will always meet as pairs, so you can list them through capture.
a source to share