从格式化的字符串生成数据

ahm*_*iee 0 c# string string-formatting c#-4.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);
Run Code Online (Sandbox Code Playgroud)

我想提取first,并last从最终的格式化字符串(f).它意味着我要脱格式f提取firstlast(我的格式为基础(s)).

有一种方式是这样的:

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

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

任何人都可以告诉我简单的方法是什么?

Tho*_*iss 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;
}
Run Code Online (Sandbox Code Playgroud)

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