1

我有一个输入字符串,其格式可以被正则表达式捕获。然后我需要用 {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 跨度,跨度类是组的捕获,跨度值也是组的捕获。IE,

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

或者

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

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

4

2 回答 2

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"
}
于 2013-11-08T17:20:18.667 回答
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>."
于 2013-11-08T17:25:29.673 回答