Check if a character is inside a source code string

  • Thread starter Thread starter Mats Bue
  • Start date Start date
M

Mats Bue

Hi

I am working on an application where I need to parse C# source code. For
example, I need to find the return statement in a method. So I search for
the word "return" in a line of code. But the problem is when the word
"return" also is found in a string (either normal or literal).

Example:
.....
if (a == 2) return true; // This should give a match
if(s == "a string with return") b = 3; // This should not give a match

So I am looking for a way (using regex?) to determine if a position in a
string (e.g. char at index 5) is inside a string or not. Have tried to come
up with something without any luck.

Any ideas would be much appreciated.
 
Hi mats

I'm not good with regex but if performance is not an issue.... you could
itenerate trought all the code one character at a time and keep track of any
quotes( " or ' ) that come up... so you keep a counter of them..

if you find one increase the counter by 1.... if it finds another one of the
same type( " or ' ).... decrease the counter.... of its of the other type
increase the counter....

so you only pickup the strings ( in this case "return" ) when the counter is
zero.

Hope that helps
 
Back
Top