I am a novice with Regex usage in C#. I want a regex to find the next keyword from a given list but which is not surrounded by the quotes.
e.g. if i have a code which looks like:
while (t < 10) { string s = 'get if stmt'; u = GetVal(t, s); for(;u<8;u++) { t++; } }
i tried using the Regex as @'(.*?)\s(FOR|WHILE|IF)\s’ but it gives me the ‘if’ as next keyword. whereas, i want to get the next keyword after while as ‘for’ and not as ‘if’ which is surrounded by quotes.
Can it be done in anyway using Regex? Or i will have to use conventional programming?
Try the following RegEx (Edit: fixed).
Note: Because this RegEx literal includes quotes, you can’t use the @ sign before the string. Remember that if you add any RegEx special chars to the string, you’ll need to double-escape them appropiatlye (e.g. \w). Insure that you also specify the Multiline parameter when matching with the RegEx, so the caret (^) is treated as the start of a new line.
This hasn’t been tested, but should do the job. Let me know if there’s any problems. Also, depending on what more you want to do here, I might recommend using standard text-parsing (non-RegEx), as it will quickly become more readable depending on how much data you want to extract from the code. Hope that helps anyway.
Edit: Here’s some example code, which I’ve tested and am pretty confident that it works as intended.
Hopefully this should be your complete solution now…