Regex matches everything except quoted string in C #

I am new to using regular expressions in C #. I want the regex to find the next keyword from a given list, but not surrounded by quotation marks.

eg. if I have code that looks like this:

            while (t < 10)
            {
                string s = "get if stmt";
                u = GetVal(t, s);
                for(;u<8;u++)
                {
                    t++;
                }

            }

I tried using Regex as @ "(. *?) \ S (FOR | WHILE | IF) \ s" but it gives me an "if" as the next keyword. while I want to get the next keyword after this as an β€œfor,” not an β€œif,” which is surrounded by quotation marks.

Is it possible to use Regex anyway? Or will I have to use regular programs?

+3
source share
5 answers

RegEx (:).

(?:[^\"]|(?:(?:.*?\"){2})*?)(?: |^)(?<kw>for|while|if)[ (]

. RegEx , @ . , RegEx , (,\w). , Multiline RegEx, (^) .

, . , . , , , ( RegEx), , . , .

Edit: , , , .

var input = "while t < 10 loop\n s => 'this is if stmt'; for u in 8..12 loop \n}"; 
var pattern = "(?:[^\"]|(?:(?:.*?\"){2})*?)(?: |^)(?<kw>for|while|if)[ (]";
var matches = Regex.Matches(input, pattern);
var firstKeyword = matches[0].Groups["kw"].Value;
// The following line is a one-line solution for .NET 3.5/C# 3.0 to get an array of all found keywords.
var keywords = matches.Cast<Match>().Select(match => match.Groups["kw"].Value).ToArray();

, ...

+2

Regex,

+1

, , , , .

, , , , . , .

0

I believe Regex cannot easily understand C # keywords. I suggest you use: Microsoft.CSharp.CSharpCodeProvider using this Visual Studio controls C # code.

0
source

Is it possible to use Regex anyway?

Generally not. C # syntax cannot be parsed by regular expressions.

Consider these corner cases:

method("xxx\"); while (\"xxx");

method(@"xxx \"); while (...);

// while

/* while */

/* xxx
// xxx */ while

/* xxx " xxx */ while ("...

Languages ​​as complex as C # need dedicated parsers.

0
source

Source: https://habr.com/ru/post/1704265/


All Articles