0

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

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

4

3 回答 3

3

The String.Replace approach should work fine and may be the best solution for you. But if you still want a regex solution, you could use something like this:

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];
}

It works on tokens such as this: ##hello##. The value between the ## are searched for in the dictionary that you provide, remember that the the search in the dictionary is case sensitive. If it is not found in the dictionary, the token is left unchanged in the string. The following code can be used to test it out:

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();

Running it will give the following output:

This is value1: 1111. Here is value2: 2222. Some fake markers here ##valueFake, here ##VALUE4## and here ####. And finally value3: 3333?

于 2013-05-22T18:06:46.753 回答
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\" />");
于 2013-05-22T11:00:24.617 回答
0

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

于 2013-05-22T11:01:07.430 回答