0

我有这个代码来格式化字符串

string s = "the first number is: {0} and the last is: {1} ";
int first = 2, last = 5;
string f = String.Format(s, first, last);

我想从first最终格式化的last字符串(fffirstlasts

有一种方法是这样的:

  • string.Split()使用(艰难和糟糕的方式)提取它们

但我认为.Net 中有一个简单的解决方案,但我不知道这是什么。

谁能告诉我简单的方法是什么?

4

3 回答 3

5

为什么不在这里使用一些正则表达式?

string s = "the first number is: {0} and the last is: {1} ";
int first = 2, last = 5;
string f = String.Format(s, first, last);

string pattern = @"the first number is: ([A-Za-z0-9\-]+) and the last is: ([A-Za-z0-9\-]+) ";
Regex regex = new Regex(pattern);
Match match = regex.Match(f);
if (match.Success)
{
    string firstMatch = match.Groups[1].Value;
    string secondMatch = match.Groups[2].Value;
}

您显然可以通过适当的错误检查使其更加健壮。

于 2012-04-15T16:48:38.960 回答
1

您可以使用正则表达式以更动态的方式实现它。

于 2012-04-15T16:24:24.167 回答
1

这是你要找的吗?

        string s = "the first number is: {0} and the last is: {1} ";
        int first = 2, last = 5;
        string f = String.Format(s, first, last);
        Regex rex = new Regex(".*the first number is: (?<first>[0-9]) and the last is: (?<second>[0-9]).*");
        var match = rex.Match(f);
        Console.WriteLine(match.Groups["first"].ToString());
        Console.WriteLine(match.Groups["second"].ToString());
        Console.ReadLine();
于 2012-04-15T16:50:39.447 回答