我有一个看起来像这样的字符串:
This is your <link>Here</link>
我想将link
标记替换为实际链接,因此我的字符串看起来像
This is your <a href='URL'>Here</a>
我正在尝试String.Replace
,但无法达到预期的输出。我该如何更换它?
答案 0 :(得分:2)
您可以使用正则表达式来捕获和替换:
var url = "www.google.com";
var oldString = "<link>Here</link>";
// Named regex capturing group
var capturePattern = "(<link>)(?<label>.*)(</link>)";
// Replace pattern that changes link tag to a tag and inserts your label
var replacePattern = "<a href='" + url + "'>${label}</a>";
var newString = Regex.Replace(oldString, capturePattern, replacePattern,
RegexOptions.IgnoreCase);
您可能希望在捕获模式时包含[ ]*
构造以避免额外的空格。例如,此捕获模式将允许您link
标记中的空格,并将修剪捕获的标签:
var capturePattern = "<[ ]*link[ ]*>[ ]*(?<label>.*)[ ]*<[ ]*/[ ]*link[ ]*>";