用HTML标记替换字符串

时间:2013-05-22 10:57:36

标签: c# html asp.net regex vb.net

我正在研究正则表达式,但它不能正常工作。 我的要求是我有一个字符串值,它有'##Anything##'个标签。 我想用asp控件替换这个##Anything##

##name##捐赠一个texbox ##Field##捐赠一个组合框 等等

3 个答案:

答案 0 :(得分:2)

String.Replace方法应该可以正常工作,可能是最适合您的解决方案。但是如果你仍然想要一个正则表达式解决方案,你可以使用这样的东西:

private const string REGEX_TOKEN_FINDER = @"##([^\s#]+)##"
private const int REGEX_GRP_KEY_NAME = 1;

public static string Format(string format, Dictionary<string, string> args) {
    return Regex.Replace(format, REGEX_TOKEN_FINDER, match => FormatMatchEvaluator(match, args));
}

private static string FormatMatchEvaluator(Match m, Dictionary<string, string> lookup) {
    string key = m.Groups[REGEX_GRP_KEY_NAME].Value;
    if (!lookup.ContainsKey(key)) {
        return m.Value;
    }
    return lookup[key];
}

它适用于这样的标记:## hello ##。在您提供的字典中搜索##之间的值,请记住字典中的搜索区分大小写。如果在字典中找不到,则令牌在字符串中保持不变。可以使用以下代码对其进行测试:

var d = new Dictionary<string, string>();
d.Add("VALUE1", "1111");
d.Add("VALUE2", "2222");
d.Add("VALUE3", "3333");

string testInput = "This is value1: ##VALUE1##. Here is value2: ##VALUE2##. Some fake markers here ##valueFake, here ##VALUE4## and here ####. And finally value3: ##VALUE3##?";

Console.WriteLine(Format(testInput, d));
Console.ReadKey();

运行它将提供以下输出:

  

这是value1:1111。这是value2:2222。这里有一些假标记## valueFake,这里## VALUE4 ##和这里####。最后是值3:3333?

答案 1 :(得分:1)

您可以使用String.Replace()方法执行此操作:

//Example Html content
string html ="<html> <body> ##Name## </body> </html>";

 //replace all the tags for AspTextbox as store the result Html
string ResultHtml = html.Replace("##Name##","<asp:Textbox id=\"txt\" Text=\"MyText\" />");

答案 2 :(得分:0)

同样,最好的提示是使用string.Replace(),也许与string.Substring()结合使用。

相关问题