如何格式化正则表达式捕获字符串,以便可以使用String.Format()进行格式化?

时间:2013-11-08 17:00:22

标签: c# regex

我有一个输入字符串,其格式可以由正则表达式捕获。然后我需要用{n}替换输入字符串的每个捕获,其中n是捕获组的编号。

我的输入字符串如下所示:

"When this Pokémon has 1/3 or less of its [HP]{mechanic:hp} remaining, its []{type:grass}-type moves inflict 1.5× as much [regular damage]{mechanic:regular-damage}."

我的输出字符串看起来有点像这样

"When this Pokémon has 1/3 or less of its {0} remaining, its {1}-type moves inflict 1.5× as much {2}."

目前,我有捕获 - \[([\s\w'-]*)\]\{([\s\w'-]*):([\s\w'-]*)\}

然而除此之外,我被惹恼了;我不知道如何继续。 对于上下文,{0}将替换为HTML范围,span类是从组中捕获,以及span值也是对组的捕获。即,

<span class="mechanic:hp">HP</span>

<span class="type:grass">Grass</span>

我怎样才能实现这个目标?

2 个答案:

答案 0 :(得分:2)

这是你要找的吗?

static void Main(string[] args)
{
    var index = 0;
    var input = "this FOO is FOO a FOO test";
    var pattern = "FOO";
    var result = Regex.Replace(input, pattern, m => "{" + (index++) + "}");

    Console.WriteLine(result); // produces "this {0} is {1} a {2} test"
}

答案 1 :(得分:0)

这将替换为{n}:

string input = "When this Pokémon has 1/3 or less of its [HP]{mechanic:hp} remaining, its []{type:grass}-type moves inflict 1.5× as much [regular damage]{mechanic:regular-damage}.";
string pattern = @"\[([\s\w'-]*)\]\{([\s\w'-]*):([\s\w'-]*)\}";

MatchCollection matches = Regex.Matches(input, pattern);
for(int i = 0; i < matches.Count; i++)
{
    input = input.Replace(matches[i].Groups[0].ToString(), "{" + i + "}");
}
Console.WriteLine(input);

输出:

"When this Pokémon has 1/3 or less of its {0} remaining, its {1}-type moves inflict 1.5× as much {2}."

如果您愿意,可以使用以下内容直接替换为跨度:

string input = "When this Pokémon has 1/3 or less of its [HP]{mechanic:hp} remaining, its []{type:grass}-type moves inflict 1.5× as much [regular damage]{mechanic:regular-damage}.";
//Note: Changed pattern to only have 2 match groups to simplify the replace
string pattern = @"\[([\s\w'-]*)\]\{([\s\w'-]*:[\s\w'-]*)\}";

MatchCollection matches = Regex.Matches(input, pattern);
for(int i = 0; i < matches.Count; i++)
{
    string spanText = matches[i].Groups[1].ToString();
    string spanClass = matches[i].Groups[2].ToString();
    input = input.Replace(matches[i].Groups[0].ToString(), "<span class=\"" + spanClass + "\">" + spanText + "</span>");
}
Console.WriteLine(input);

输出:

"When this Pokémon has 1/3 or less of its <span class=\"mechanic:hp\">HP</span> remaining, its <span class=\"type:grass\"></span>-type moves inflict 1.5× as much <span class=\"mechanic:regular-damage\">regular damage</span>."
相关问题