我有一些包含缩写的网站内容。我有该网站公认的缩写列表及其解释。我想创建一个正则表达式,它允许我用一些标记替换内容中找到的所有可识别的缩写。
例如:
内容:
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;
result:
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.
(为了简单起见,这只是示例标记)。
Thanks.
EDIT:
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()还不够 - 但我可以明白为什么正则表达式是可取的:您可以使用它来强制“整个单词”替换,只需创建一个使用单词边界锚的模式。
您甚至可以从所有转义的输入字符串构建单个模式,如下所示:
\b(?:{abbr_1}|{abbr_2}|{abbr_3}|{abbr_n})\b
然后使用比赛评估员找到合适的替代品。这样您就可以避免多次迭代输入字符串。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)