是否可以存储正则表达式匹配并将其一部分用作列表枚举器?

时间:2018-07-13 12:52:33

标签: c# regex

我创建了一个MadLibs风格的游戏,用户输入对提示的响应,这些提示又替换了故事中用%s0,%s1等表示的空格。我使用for循环进行此工作,但其他人建议我可以使用正则表达式来完成。我到目前为止的内容在下面,它将所有%s + number实例替换为“ wibble”。我想知道的是,是否可以将正则表达式找到的数字存储在一个临时变量中,然后使用该数字从单词列表中返回一个值?例如。 return Regex.Replace(story, pattern, Global.Words[x]);,其中x是正则表达式模式遍历字符串时返回的数字。

    static void Main(string[] args)
    {

        Globals.Words = new List<string>();
        Globals.Words.Add("nathan");
        Globals.Words.Add("bob");

        var text = "Once upon a time there was a %s0 and it was %s1";
        Console.WriteLine(FindEscapeCharacters(text));
    }

    public static string FindEscapeCharacters(string story)
    {
        var pattern = @"%s([0-9]+)";
        return Regex.Replace(story, "%s([0-9]+)", "wibble");
    }

预先感谢,内森。

3 个答案:

答案 0 :(得分:4)

不是您对正则表达式问题的直接答案,但是如果我对您的理解正确,那么有一种更简单的方法可以做到这一点:

string baseString = "I have a {0} {1} in my {0} {2}.";

List<string> words = new List<string>() { "red", "cat", "hat" };

string outputString = String.Format(baseString, words.ToArray());

outputString将是I have a red cat in my red hat.

这不是您想要的,还是我想念的还有更多疑问?


小细节

String.Format使用以下签名:

string Format(string format, params object[] values)

params的好处是,您可以分别列出值:

var a = String.Format("...", valueA, valueB, valueC);

但是您也可以直接传递数组:

var a = String.Format("...", valueArray);

请注意,您不能混合使用两种方法。

答案 1 :(得分:2)

是的,您与Regex.Replace的尝试非常接近;最后一步是将常数 "wibble"更改为 lambda match => how_to_replace_the_match

  var text = "Once upon a time there was a %s0 and it was %s1";

  // Once upon a time there was a nathan and it was bob
  var result = Regex.Replace(
    text, 
   "%s([0-9]+)", 
    match => Globals.Words[int.Parse(match.Groups[1].Value)]);

编辑::如果您不想使用按其编号捕获组,则可以对其进行明确命名

  // Once upon a time there was a nathan and it was bob
  var result = Regex.Replace(
    text, 
   "%s(?<number>[0-9]+)", 
    match => Globals.Words[int.Parse(match.Groups["number"].Value)]);

答案 2 :(得分:0)

an overload of Regex.Replace,而不是最后一个参数采用字符串,而是采用了MatchEvaluator委托-该函数采用Match对象并返回string

您可以使该函数解析Match的{​​{1}}属性中的整数,然后使用它索引到列表中,返回找到的Groups[1].Value