Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何在有特殊条件的C中使用正则表达式突出显示关键字?_C#_Regex_Syntax Highlighting - Fatal编程技术网

C# 如何在有特殊条件的C中使用正则表达式突出显示关键字?

C# 如何在有特殊条件的C中使用正则表达式突出显示关键字?,c#,regex,syntax-highlighting,C#,Regex,Syntax Highlighting,我是Regex的新手,所以我需要一些麻烦的帮助 这是我的代码: private static string MatchEval(Match match) { if (match.Groups[1].Success) return "<strong>" + match.ToString() + "</strong>"; return ""; } private static string HighlightKeywords(stri

我是Regex的新手,所以我需要一些麻烦的帮助

这是我的代码:

private static string MatchEval(Match match)
{
    if (match.Groups[1].Success)    
        return "<strong>" + match.ToString() + "</strong>";
    return "";
}

private static string HighlightKeywords(string keywords, string text)
{   
    Regex r = new Regex(@", ?");
    keywords = "(" + r.Replace(keywords, @"|") + ")";   
    r = new Regex(keywords, RegexOptions.Singleline | RegexOptions.IgnoreCase); 
    return r.Replace(text, new MatchEvaluator(MatchEval));
}

string keywords = "group, person, club";
string text = "A fan club is a group that is dedicated to a well-known person";
当我调用HighlightKeywords字符串关键字时,字符串文本

->结果:粉丝俱乐部是一个致力于名人的团体 工作正确

但如果string text=粉丝俱乐部是一个致力于名人的团体

->结果:粉丝俱乐部是一个致力于名人的团体

工作失败,我想移除只有球杆的球杆

另一种情况是,如果text=A fanclub是一个专门为知名人士服务的团体; 注:fanclub无空间

结果->fanclub是一个致力于名人的团体

但我想得到结果->fanclub是一个致力于名人的团体

有人能帮我怎么做吗?

你可以试试这个:

keywords = "\b(" + r.Replace(keywords, @"|") + ")\b";
\b-对于非单词字符,您可以尝试以下方法:

keywords = "\b(" + r.Replace(keywords, @"|") + ")\b";

\b-对于非单词字符

您的关键字应如下所示

string keywords = "\bgroup\b, \bperson\b, \bclub\b";

\b将创建一个边界,使fanclub不匹配

您的关键字应该是这样的

string keywords = "\bgroup\b, \bperson\b, \bclub\b";

\b将创建一个边界,使fanclub不匹配

你试过什么?您似乎没有试图自己纠正故障,因为对于编写您已有的内容的人来说,修复应该是微不足道的。那么您尝试了什么呢?您似乎没有试图自己纠正故障,因为对于编写您已有的内容的人来说,修复应该是微不足道的。如果您正在查找非强匹配项,可以添加look behind:keywords=?\b+r.Replacekeywords,@|+\b;如果要查找非强匹配项,可以添加look-behind:keywords=?\b+r.Replacekeywords,@|+\b;