首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在具有特殊条件的C#中使用Regex关键字突出显示?

如何在具有特殊条件的C#中使用Regex关键字突出显示?
EN

Stack Overflow用户
提问于 2012-08-22 18:10:04
回答 2查看 772关注 0票数 2

我是Regex的新手,所以我需要从我的麻烦中得到帮助。

这是我的密码:

代码语言:javascript
复制
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 keywords, string text);

->结果:A fan <strong>club</strong> is a <strong>group</strong> that is dedicated to a well-known <strong>person</strong> 工作正确

但如果string text = "A fan <strong>club</strong> is a group that is dedicated to a well-known person";

->结果:A fan <strong></strong><strong>club</strong> is a <strong>group</strong> that is dedicated to a well-known <strong>person</strong>

工作失败(我希望仅用<strong>club</strong>删除<strong></strong><strong>club</strong> )

另一个案例if text = "A fanclub is a group that is dedicated to a well-known person";注:“扇俱乐部”没有空格

结果-> A fan<strong>club</strong> is a <strong>group</strong> that is dedicated to a well-known <strong>person</strong>

但我想得到结果-> A fanclub is a <strong>group</strong> that is dedicated to a well-known <strong>person</strong>

有人能帮我做这件事吗?

EN

回答 2

Stack Overflow用户

发布于 2012-08-22 18:27:11

你可以试试这个:

代码语言:javascript
复制
keywords = "\b(" + r.Replace(keywords, @"|") + ")\b";

\b -用于非字字符

票数 0
EN

Stack Overflow用户

发布于 2012-08-22 18:36:54

你的关键词应该是这样

代码语言:javascript
复制
string keywords = "\bgroup\b, \bperson\b, \bclub\b";

\b会创建一个边界,这样fanclub就不匹配了!

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/12078961

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档