0

Hi I am trying to create an App to help me switch out the test contents of my Catch-Block and replace them with production contents. I am able to read through my file, and parse the contents, but having problems creating a regex( I am brand new to this still) to identify the try-catch block, so I can either choose to delete or change the contents of the catch block. Anyone able to help me solve this problem please??

so far I have the expression below(does not work at all)

try{*}catch(*){*)

Thanks in advance.

Kobojunkie
  • 6,375
  • 31
  • 109
  • 164
  • Could you also post some of the C# code you're using to delete/replace the contents? – WLin Feb 23 '13 at 03:48
  • I have yet to put that part together. I am stuck on identifying the try-Catch or try-Catch Finally in the text file. I read the try-catches into a queue. Then I loop through the queue to make sure that the content is really valid. Since I have not gotten the regex right, I am stuck there. – Kobojunkie Feb 23 '13 at 03:51

3 Answers3

3

You can't write a regex that does this, because regex can't be used to match nested patterns. Which means that it won't be able to identify when your closing brace occurs vs other nested braces in your code. You will need a parser generator such as ANTLR like the linked answer suggests to accomplish this.

Community
  • 1
  • 1
lmortenson
  • 1,610
  • 11
  • 11
  • I remember from Automata class, I learned how to parse open and closing braces in a file. I figured since that can be done, then it should be possible to use a regex to do something like that. Or am I wrong? – Kobojunkie Feb 23 '13 at 03:57
  • Regexes can't keep a count of how many open braces vs close braces they have seen, so they aren't suitable for that task. – lmortenson Feb 23 '13 at 03:58
1

I'd suggest taking a look at Microsoft's Roslyn compiler that is under development. It's APIs should probably allow you to accomplish whatever it is you're looking to do. It is currently in preview.

MgSam
  • 12,139
  • 19
  • 64
  • 95
0

I think this would drive you to a solution:

try\s*\{[^{}]*([^{}]*\{[^{}]*\}[^{}]*)*[^{}]*\}\s*catch\s*\([^()]*(\([^()]*\))*\)\s*\{[^{}]*([^{}]*\{[^{}]*\}[^{}]*)*[^{}]*\}

try\s* matches try followed by zero or more spaces.

\{[^{}]*([^{}]*\{[^{}]*\}[^{}]*)*[^{}]*\} matches a block ({ followed by zero or more characters except { and } followed by zero or more blocks with any number of characters preceding and succeeding each)

\s*catch\s*\([^()]*(\([^()]*\))*\) matches zero or more spaces preceding and following catch, then something inside brackets ()

\s*\{[^{}]*([^{}]*\{[^{}]*\}[^{}]*)*[^{}]*\} similar to try block

Note: May fail in case of ones with comments containing {s or }s

Naveed S
  • 5,106
  • 4
  • 34
  • 52