用html标签替换字符===文本的任一侧

时间:2014-01-10 11:10:17

标签: c# regex

我真的很难找到一种方法让下面的工作,我有以下格式的一些数据===一些文本===我想用html标签替换文本周围的===。

我尝试过使用Match and replace,但是我得到了一个糟糕的编译常量值,我也尝试了Replace {tag} with a value or completely remove {any-tag},但这只删除了所有文本。我也试过http://www.rexegg.com/regex-lookarounds.html但没有工作,我认为我遇到的问题是因为文本周围的标签没有结束标签我无法找到文本

所以我尝试过这样的事情:

string format = Regex.Replace(data.FirstOrDefault().countrylist, "=== This could be any text ===", " </p><p class=\"strong\">Need to keep text here<p>");  

文本外观的示例:

====罗马帝国的兴衰====

==== 20世纪和21世纪====

所以我希望它看起来:

</p><p class=\"strong\">Rise and fall of the Roman empire<p>
</p><p class=\"strong\">20th and 21st centuries<p>

我不是正则表达式中最伟大的,我的所有尝试都失败了,所以任何帮助都会受到高度赞赏。

2 个答案:

答案 0 :(得分:1)

试试这个:

var yourstring = "===20th and 21st centuries===";
var regex = new Regex(Regex.Escape("==="));
// The last 1 tells to replace only the first occurence of the Escape
yourstring = regex.Replace(yourstring, "</p><p class=\"strong\">", 1);
yourstring = regex.Replace(yourstring, "<p>", 1);

不要忘记错误处理,我不知道如果它想要替换出现并且找不到它会发生什么

编辑:如果你有多个应该被替换的条目,循环替换部分直到它不能再替换它然后它会抛出你可以抓住继续的错误

答案 1 :(得分:0)

以下内容适用于我的环境:

    string text = "===Rise and fall of the Roman empire===";
    var pattern = @"===(.*)===";
    var regex = new Regex(pattern);
    var match = regex.Match(text);
    var result = string.Concat("</p><p class=\"strong\">", match.Groups[1].Value, "<p>");

此致