2012-04-15 80 views
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); 

我想從最終格式的字符串提取firstlastf)。它是指欲去格式化的f提取firstlast(我有格式庫(s))。

還有一種方式是這樣的:(硬和壞的方式)

  • 使用string.Split()提取它們,但我認爲這是在.net中一個簡單的解決辦法,但我不知道知道這是什麼。

    有人能告訴我什麼是簡單的方法嗎?

+0

未來,如果您編輯舊問題而不是刪除它並創建一個新問題會更好。 – svick 2012-04-15 15:30:56

+0

另外,爲什麼你甚至試圖做到這一點?可能有更好的解決方案。 – svick 2012-04-15 15:31:54

+0

@svick:它得到-3票,因爲我沒有告訴我的問題是正確的。如果我這樣做,它得到更多的-3票,我無法得到我的答案:( – 2012-04-15 15:32:29

回答

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; 
} 

通過適當的錯誤檢查,您顯然可以使其更健壯。

1

您可以使用正則表達式以更動態的方式實現它。

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(); 
+0

no有更好的**方法,第一個和最後一個的類型是樣本 – 2012-04-15 17:05:59

+0

我或者'我沒有正確解釋你,反之亦然......我所做的是給你一種檢索命名組合的方法ps從正則表達式的名字。在正則表達式中,這就是尖括號的意思。這樣你可以避免使用int索引器。我不確定你在回覆中的意思......無論如何,我看到你有一個解決方案,所以不管。 – 2012-04-17 07:37:14