【发布时间】:2011-08-18 06:42:15
【问题描述】:
我有一个关键字列表(单个词或几个词),我想用一些 URL 替换它们。
喜欢:
伦敦将替换为
<a href="http://www.mysite/london-events/london">London</a><a href="http://www.mysite/footbal-events/london"> Football events in London</a><a href="http://www.mysite/footbal-events/london"> Football events in London</a>伦敦的足球赛事伦敦足球赛事
<a href="http://www.mysite/footbal-events/london"> London football events</a>伦敦足球赛事
<a href="http://www.mysite/footbal-events/london"> Football events London</a><a href="http://www.mysite/party-sites/london"> party sites in London</a>伦敦的派对网站伦敦派对网站
<a href="http://www.mysite/party-sites/london"> London party sites</a>
我将上面的键/值放在字典中,关键字放在键中,将 URL 放在值中并替换为类似
内容如下:
伦敦是一座伟大的城市,拥有 伦敦的足球赛事,但派对 伦敦的网站也不错。伦敦 足球赛事很棒 伦敦派对网站。享受伦敦!
替换键/值的代码:
private static string ParsedContents(some arguments list here...)
{
Dictionary<string, string> keyWords = GetKeywordsAndEntityWithURL(some arguments list here...);
StringBuilder parsedContents = new StringBuilder(contents);
foreach (var keyWord in keyWords)
{
string replacedString = Regex.Replace(parsedContents.ToString(), "\\b" + keyWord.Key + "\\b", keyWord.Value, RegexOptions.IgnoreCase);
parsedContents.Remove(0, parsedContents.Length);
parsedContents.Append(replacedString);
}
// retrun parsed contents as string.
return parsedContents.ToString();
}
当我运行我的代码时,只有 'London' 替换为 '<a href="http://www.mysite/london-events/london">London</a>' 并且所有其他都保持不变,但如果我从关键字中删除 'London' 它工作正常。
你能帮我弄清楚如何匹配整个字符串。
要替换的内容和网址是假的:
谢谢
【问题讨论】:
-
如果某些关键字是其他关键字的子集(例如,“London”和“London party sites”),那么“London”可以匹配“London party sites”并搞砸一切。您的方法需要牢记这一点并妥善处理,至少通过将字典键从最长到最短排序。
标签: c# .net regex c#-3.0 replace