正则表达式找到非关键字

问题描述 投票:0回答:1

我可以使用这样的模式来找到关键词:

//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';

但我如何找到非关键词,如abcclass_defgh

c# regex match
1个回答
3
投票

我认为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));
© www.soinside.com 2019 - 2024. All rights reserved.