C# 在字符串中的某些单词周围插入HTML标记
假设我有两个字符串: “此处有些文字”和“此处有些文字” 我有一个集合,其中包含我希望与字符串中的文本匹配的单词。 “一些”、“文本”、“此处” 如果其中一个单词与字符串中的某个单词匹配(无论是大写还是小写),我希望从字符串中提取原始单词,并在其周围添加一些HTML标记,如下图所示C# 在字符串中的某些单词周围插入HTML标记,c#,html,regex,C#,Html,Regex,假设我有两个字符串: “此处有些文字”和“此处有些文字” 我有一个集合,其中包含我希望与字符串中的文本匹配的单词。 “一些”、“文本”、“此处” 如果其中一个单词与字符串中的某个单词匹配(无论是大写还是小写),我希望从字符串中提取原始单词,并在其周围添加一些HTML标记,如下图所示原始单词 我在玩弄string.Replace()方法,但不确定如何让它匹配,而不考虑大小写,以及如何保持原始单词的完整性(这样我就不会用word替换“word”),您可以使用正则表达式: class Program
原始单词
我在玩弄string.Replace()方法,但不确定如何让它匹配,而不考虑大小写,以及如何保持原始单词的完整性(这样我就不会用
word替换“word”),您可以使用正则表达式:
class Program {
static string ReplaceWord(Match m) {
return string.Format("<dfn>{0}</dfn>",m.Value);
}
static void Main(string[] args) {
Regex r = new Regex("some|text|here", RegexOptions.IgnoreCase);
string input = "Some random text.";
string replaced = r.Replace(input, ReplaceWord);
Console.WriteLine(replaced);
}
}
类程序{
静态字符串替换字(匹配m){
返回string.Format(“{0}”,m.Value);
}
静态void Main(字符串[]参数){
Regex r=new Regex(“some | text | here”,RegexOptions.IgnoreCase);
字符串输入=“一些随机文本。”;
字符串替换=r.Replace(输入,ReplaceWord);
控制台写入线(已更换);
}
}
RegexOptions.IgnoreCase
用于匹配列表中的单词,而不考虑其大小写。
ReplaceWord
函数返回由开头和结尾标记包围的匹配字符串(大小写正确)(请注意,您可能仍需要转义内部字符串)。您可以使用正则表达式:
class Program {
static string ReplaceWord(Match m) {
return string.Format("<dfn>{0}</dfn>",m.Value);
}
static void Main(string[] args) {
Regex r = new Regex("some|text|here", RegexOptions.IgnoreCase);
string input = "Some random text.";
string replaced = r.Replace(input, ReplaceWord);
Console.WriteLine(replaced);
}
}
类程序{
静态字符串替换字(匹配m){
返回string.Format(“{0}”,m.Value);
}
静态void Main(字符串[]参数){
Regex r=new Regex(“some | text | here”,RegexOptions.IgnoreCase);
字符串输入=“一些随机文本。”;
字符串替换=r.Replace(输入,ReplaceWord);
控制台写入线(已更换);
}
}
RegexOptions.IgnoreCase
用于匹配列表中的单词,而不考虑其大小写。
ReplaceWord
函数返回由开头和结尾标记包围的匹配字符串(大小写正确)(请注意,您可能仍需要转义内部字符串).事实上,string.Replace
方法的通用性不足以满足您在这种情况下的需求。较低级别的文本操作应该可以完成这项工作。替代方法当然是正则表达式,但我在这里介绍的算法将是最有效的方法,我认为无论如何编写它都会有帮助,以了解如何使用大量的文本操作没有正则表达式进行更改
这里是函数
更新:
现在使用的是字典
,而不是字符串[]
,这样可以将定义与单词一起传递给函数
现在可以对字典中的定义进行任意排序
publicstaticstringhtmlreplace(字符串值,字典
定义,函数(htmlWrapper)
{
var sb=新的StringBuilder(值.Length);
int指数=-1;
int lastEndIndex=0;
键值对def;
而((index=IndexOf)(值、定义、lastEndIndex、,
StringComparison.InvariantCultureIgnoreCase,out def))!=-1)
{
sb.Append(value.Substring(lastEndIndex,index-lastEndIndex));
sb.Append(htmlWrapper(def.Key,def.Value));
lastEndIndex=index+def.Key.Length;
}
sb.Append(value.Substring(lastEndIndex,value.Length-lastEndIndex));
使某人返回字符串();
}
私有静态int IndexOf(字符串文本、字典值、int startIndex、,
StringComparison比较类型,out KeyValuePair foundEntry)
{
var minEntry=默认值(KeyValuePair);
int minIndex=-1;
整数指数;
foreach(值中的var条目)
{
如果((index=text.IndexOf(entry.Key,startIndex,comparisonType))
和一个小的测试程序。(注意为了方便起见使用了lambda表达式。)
static void Main(字符串[]args)
{
var str=“定义foo;定义栏;定义baz”;
var definitions=newdictionary();
定义。添加(“foo”、“定义1”);
定义。添加(“条”、“定义2”);
定义。添加(“baz”、“定义3”);
var输出=HtmlReplace(str,定义,
(单词,定义)=>string.Format(“{0}”,
词汇、定义);
}
输出文本:
定义foo;定义栏;定义baz
希望这会有所帮助。事实上,string.Replace
方法的通用性不足以满足您在这种情况下的需求。较低级别的文本操作应该可以完成这项工作。替代方法当然是正则表达式,但我在这里介绍的算法将是最有效的方法,我认为将其编写到了解如何在不使用正则表达式的情况下进行大量文本操作以进行更改
这里是函数
更新:
现在使用的是字典
,而不是字符串[]
,这样可以将定义与单词一起传递给函数
现在可以对字典中的定义进行任意排序
publicstaticstringhtmlreplace(字符串值,字典
定义,函数(htmlWrapper)
{
var sb=新的StringBuilder(值.Length);
int指数=-1;
int lastEndIndex=0;
键值对def;
而((index=IndexOf)(值、定义、lastEndIndex、,
StringComparison.InvariantCultureIgnoreCase,out def))!=-1)
{
sb.Append(value.Substring(lastEndIndex,index-lastEndIndex));
sb.Append(htmlWrapper(def.Key,def.Value));
lastEndIndex=index+def.Key.Length;
}
sb.Append(value.Substring(lastEndIndex,value.Length-lastEndIndex));
使某人返回字符串();
}
私有静态int IndexOf(字符串文本,
static void Main(string[] args)
{
var str = "Definition foo; Definition bar; Definition baz";
var definitions = new Dictionary<string, string>();
definitions.Add("foo", "Definition 1");
definitions.Add("bar", "Definition 2");
definitions.Add("baz", "Definition 3");
var output = HtmlReplace(str, definitions,
(word, definition) => string.Format("<dfn title=\"{1}\">{0}</dfn>",
word, definition));
}
static string IgnoreCaseReplace(string text, string oldValue, string newValue)
{
int index = 0;
while ((index = text.IndexOf(oldValue,
index,
StringComparison.InvariantCultureIgnoreCase)) >= 0)
{
text = text.Substring(0, index)
+ newValue
+ text.Substring(index + oldValue.Length);
index += newValue.Length;
}
return text;
}
static class MyStringUtilities
{
public static string IgnoreCaseReplace(this string text, string oldValue, string newValue)
{
int index = 0;
while ((index = text.IndexOf(oldValue,
index,
StringComparison.InvariantCultureIgnoreCase)) >= 0)
{
text = text.Substring(0, index)
+ newValue
+ text.Substring(index + oldValue.Length);
index += newValue.Length;
}
return text;
}
}
/// <summary>
/// Converts the input string by formatting the words in the dict with their meanings
/// </summary>
/// <param name="input">Input string</param>
/// <param name="dict">Dictionary contains words as keys and meanings as values</param>
/// <returns>Formatted string</returns>
public static string FormatForDefns(string input, Dictionary<string,string> dict )
{
string formatted = input;
foreach (KeyValuePair<string, string> kv in dict)
{
string definition = "<dfn title=\"" + kv.Value + "\">" + kv.Key + "</dfn>.";
string pattern = "(?<word>" + kv.Key + ")";
formatted = Regex.Replace(formatted, pattern, definition, RegexOptions.IgnoreCase);
}
return formatted;
}
Dictionary<string, string> dict = new Dictionary<string, string>();
dict.Add("word", "meaning");
dict.Add("taciturn ", "Habitually silent; not inclined to talk");
string s = "word abase";
string formattedString = MyRegEx.FormatForDefns(s, dict);
Web Browser
Browser History
Now, clean the web browser history by ...
Now, clean the <dfn title="Definition of word">web <dfn title="Definition of word">browser</dfn> history</dfn> by ...