我可以使用这样的模式来找到关键词:
//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';
但我如何找到非关键词,如abc
,class_
,def
,gh
我认为RegEx不是这个用例的好方法。
关键字维护不好,模式随着关键字的数量增长而变慢,与Contains()
相比。
请使用string[]
List<string>
或HashSet<string>
作为关键字。
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));