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