我有一些包含缩写的网站内容。我有一个网站公认的缩写列表,以及它们的解释。我想创建一个正则表达式,它允许我用一些标记替换内容中发现的所有可识别缩写。
例如:
内容:
This is just a little test of the memb to see if it gets picked up. Deb of course should also be caught here.
缩写:
memb = Member; deb = Debut;
结果:
This is just a little test of the [a title="Member"]memb[/a] to see if it gets picked up. [a title="Debut"]Deb[/a] of course should also be caught here.
(为简单起见,这只是示例标记)。
谢谢。
编辑:
CraigD 的答案已经差不多了,但还有一些问题。我只想匹配整个单词。我还想保持替换的每个单词的大小写正确,这样 deb 仍然是 deb,Deb 仍然是原文中的 Deb。例如,这个输入:
This is just a little test of the memb. And another memb, but not amemba. Deb of course should also be caught here.deb!
最佳答案
首先你需要Regex.Escape()
所有输入字符串。
然后您可以在字符串中查找它们,并用您想到的标记迭代替换它们:
string abbr = "memb";
string word = "Member";
string pattern = String.Format("\b{0}\b", Regex.Escape(abbr));
string substitue = String.Format("[a title=\"{0}\"]{1}[/a]", word, abbr);
string output = Regex.Replace(input, pattern, substitue);
编辑:我问是否有一个简单的 String.Replace()
这还不够 - 但我可以理解为什么正则表达式是可取的:您可以使用它来强制执行“整个单词”替换,只需制作一个使用单词边界 anchor 的模式。
您可以从所有转义的输入字符串中构建一个单一模式,如下所示:
\b(?:{abbr_1}|{abbr_2}|{abbr_3}|{abbr_n})\b
然后使用 match evaluator找到合适的替代品。这样您就可以避免多次迭代输入字符串。
关于c# - 在 C# 中使用正则表达式突出显示单词列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/653700/