1

像:

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

如何获得“年龄”之后的内容?我只想要数字。(他的年龄)

4

4 回答 4

5

使用正则表达式:

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

第一个分组将返回年龄,请参见此处此处

于 2012-11-09T08:21:46.753 回答
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);
}

稳健的做法是得到一些正则表达式:)虽然......

于 2012-11-09T08:30:20.540 回答
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");

MessageBox 向您展示您的字符串值(如果找到)..

于 2012-11-09T08:36:46.847 回答
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"]);
于 2012-11-09T08:37:26.093 回答