搜索一个字符串,用它自己的副本替换一个单词的实例,用 HTML 标签包围
Searching a string, replacing instances of a word with a copy of itself, surrounded by HTML tags
我的问题是我想解析一个大字符串,找到该字符串中某个单词的所有实例,然后在其周围插入标签,以便在 ASP.Net 中显示时突出显示MVC 4 视图。下面代码的问题是,如果我搜索一个词并使用与段落中不同的大小写,它会找到它,但会用我最初搜索的任何大小写替换它。
例如,在下面的段落中,有两个单词 "lectus"。
- 如果我搜索“lectus”,它会找到它并将其替换为“lectus”。没关系。
- 但是,如果我搜索“LECTUS”,它将找到 "lectus" 的两个实例并将其替换为“LECTUS".
我想要做的是让它与单词匹配,插入标签,但保持原始单词原样 - 不要更改它,只需找到它并在其周围环绕文字。有没有已经支持这个的方法或功能?我似乎找不到一个...所有结果都指向不区分大小写的字符串替换,这是我已经在使用的。
// I want to find all instances of the word "lectus".
string wordToFind = "lectus";
// This is the paragraph to search...
string paragraph = "Phasellus vitae elit maximus, egestas nibh id, pretium lacus. Aliquam ac lectus quis urna pharetra consectetur. Mauris neque est, tempor ac urna quis, fringilla congue diam. Curabitur dictum arcu vitae purus pretium consectetur. In rutrum lectus neque, eget maximus nunc commodo in.";
// This searches the paragraph and replaces all instances of wordToFind with itself, wrapped in <span> tags for highlighting.
paragraph.text = Regex.Replace(paragraph.text, wordToFind, "<span style='background-color: #FFFF00'>" + wordToFind + "</span>", RegexOptions.IgnoreCase);
您可以使用 substitution symbol [=11=]
来完成,它对应于您的正则表达式捕获的值:
paragraph.text = Regex.Replace(paragraph.text, wordToFind, "<span style='background-color: #FFFF00'>[=10=]</span>", RegexOptions.IgnoreCase);
我的问题是我想解析一个大字符串,找到该字符串中某个单词的所有实例,然后在其周围插入标签,以便在 ASP.Net 中显示时突出显示MVC 4 视图。下面代码的问题是,如果我搜索一个词并使用与段落中不同的大小写,它会找到它,但会用我最初搜索的任何大小写替换它。
例如,在下面的段落中,有两个单词 "lectus"。
- 如果我搜索“lectus”,它会找到它并将其替换为“lectus”。没关系。
- 但是,如果我搜索“LECTUS”,它将找到 "lectus" 的两个实例并将其替换为“LECTUS".
我想要做的是让它与单词匹配,插入标签,但保持原始单词原样 - 不要更改它,只需找到它并在其周围环绕文字。有没有已经支持这个的方法或功能?我似乎找不到一个...所有结果都指向不区分大小写的字符串替换,这是我已经在使用的。
// I want to find all instances of the word "lectus".
string wordToFind = "lectus";
// This is the paragraph to search...
string paragraph = "Phasellus vitae elit maximus, egestas nibh id, pretium lacus. Aliquam ac lectus quis urna pharetra consectetur. Mauris neque est, tempor ac urna quis, fringilla congue diam. Curabitur dictum arcu vitae purus pretium consectetur. In rutrum lectus neque, eget maximus nunc commodo in.";
// This searches the paragraph and replaces all instances of wordToFind with itself, wrapped in <span> tags for highlighting.
paragraph.text = Regex.Replace(paragraph.text, wordToFind, "<span style='background-color: #FFFF00'>" + wordToFind + "</span>", RegexOptions.IgnoreCase);
您可以使用 substitution symbol [=11=]
来完成,它对应于您的正则表达式捕获的值:
paragraph.text = Regex.Replace(paragraph.text, wordToFind, "<span style='background-color: #FFFF00'>[=10=]</span>", RegexOptions.IgnoreCase);