在标签之间查找文本并将其与标签一起替换

我使用以下正则表达式模式在[code][/code]标签之间查找文本:

 (?<=[code]).*?(?=[/code]) 

它返回我在这两个标签之间的任何内容,例如: [code]return Hi There;[/code]给我return Hi There;

我需要有关正则表达式的帮助来替换整个文本以及标签。

用这个:

 var s = "My temp folder is: [code]Path.GetTempPath()[/code]"; var result = Regex.Replace(s, @"\[code](.*?)\[/code]", m => { var codeString = m.Groups[1].Value; // then you have to evaluate this string return EvaluateMyCode(codeString) }); 

我会为此使用HTML Parser。 我可以看到你想要做的事情很简单,但这些事情习惯于加class加倍。 对于那些必须在未来维护代码的穷人来说,最终结果是非常痛苦的。

看看有关HTML Parsers的这个问题
在C#中解析html的最佳方法是什么?

[编辑]
以下是对所提问题的更为相关的答案。 @Milad Naseri正则表达式是正确的你只需要做类似的事情

 string matchCodeTag = @"\[code\](.*?)\[/code\]"; string textToReplace = "[code]The Ape Men are comming[/code]"; string replaceWith = "Keep Calm"; string output = Regex.Replace(textToReplace, matchCodeTag, replaceWith); 

查看此网站以获取更多示例
http://www.dotnetperls.com/regex-replace
http://oreilly.com/windows/archive/csharp-regular-expressions.html

希望这可以帮助

你需要使用反向引用,即将< \[code\](.*?)\[/code\]替换为$1 ,它将为你提供[code][/code]所包含的内容[code][/code]标签包含在 – 例如 – 标签中。