2012-11-09 60 views
1

像:如何搜索字符串中的單詞,然後獲取該單詞之後的數字?

"Name: Daniel --- Phone Number: 3128623432 --- Age: 12 --- Occupation: Student" 

如何得到的是 「時代」 之後?我只想要數字。 (他的年齡)

+0

聽起來像是正則表達式的工作:) – Mr47

+0

使用String.IndexOf http://www.dotnetperls.com/indexof – user629926

+0

http://stackoverflow.com/questions/4734116/c-sharp-find-and-extract-number-from-a-string在這裏找到靈感 – Pavenhimself

回答

5

使用表達式:

^.+Age\: ([0-9]+).+$ 

第一組將返回歲的時候,看到herehere

0

你可以嘗試一個完整的代碼如下概念:

string strAge; 
string myString = "Name: Daniel --- Phone Number: 3128623432 --- Age: 12 --- Occupation: Student"; 
int posString = myString.IndexOf("Age: "); 

if (posString >0) 
{ 
    strAge = myString.Substring(posString); 
} 

做的可靠的方法是讓一些正則表達式:)雖然...

+0

@Abatishchev:神奇RegEx編輯器:)不錯! – bonCodigo

0

假設你有年齡在這種格式Age: value

string st = "Name: Daniel --- Phone Number: 3128623432 --- Age: 12 --- Occupation: Student"; 
//Following Expression finds a match for a number value followed by `Age:` 
System.Text.RegularExpressions.Match mt = System.Text.RegularExpressions.Regex.Match(st, @"Age\: \d+"); 
int age=0; string ans = ""; 
if(mt.ToString().Length>0) 
{ 
    ans = mt.ToString().Split(' ')[1]); 
    age = Convert.ToInt32(ans); 
    MessageBox.Show("Age = " + age); 
} 
else 
    MessageBox.Show("No Value found for age"); 

MessgeBox告訴你,你的字符串值(如果找到)..

0

其實你有數據,這些數據可以很容易地表示爲Dictionary<string, string>類型的詞典:

var s = "Name: Daniel --- Phone Number: 3128623432 --- Age: 12 --- Occupation: Student"; 
var dictionary = s.Split(new string[] { "---" }, StringSplitOptions.None) 
        .Select(x => x.Split(':')) 
        .ToDictionary(x => x[0].Trim(), x => x[1].Trim()); 

現在你可以從你的輸入字符串得到任何值:

string occupation = dictionary["Occupation"]; 
int age = Int32.Parse(dictionary["Age"]); 
+0

這是一個很好且可能的解決方案,但OP可能沒有準備好變量數據(從第三方獲取信息)。 –

+0

字符串來自哪裏並沒有什麼區別。作爲最終結果,我們將有一個變量引用字符串數據:) –

相關問題