DaveG
DaveG

Reputation: 501

Regex to find non-keyword

I can use pattern like this to find key word:

//find keyword
line = @"abc class class_ def this gh static";
string Pattern;
MatchCollection M1;
Pattern = @"(?<![a-zA-Z0-9_])(class|function|static|this|return)(?![a-zA-Z0-9_])";
M1 = Regex.Matches(line, Pattern);
for (int i = 0; i < M1.Count; i++)
    output += M1[i].ToString() + '\n';

But how can I find non-keyword like abc,class_,def,gh

Upvotes: 0

Views: 74

Answers (1)

fubo
fubo

Reputation: 45977

I don't think RegEx is a good approach for this use case.

The keywords are bad to maintain and the pattern grows with the number of keywords and gets slower Compared to a Contains().

Use a string[] List<string> or HashSet<string> for your keywords instead.

string line = @"abc class class_ def this gh static";
string[] keywords = { "class", "function", "static", "this", "return" };

string outputexclude = string.Join("\n", line.Split().Where(x => !keywords.Contains(x)));
string outputinclude = string.Join("\n", line.Split().Where(keywords.Contains));

Upvotes: 3

Related Questions