簡體   English   中英

如何搜索字符串中的單詞,然后獲得該單詞之后的數字?

[英]How to search for a word in a string and then get the numbers after this word?

喜歡:

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

如何獲得“年齡”之后的信息? 我只想要數字。 (他的年齡)

使用RegEx:

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

第一次分組將返回年齡,請參見此處此處

您能否嘗試以下概念的完整代碼:

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

健壯的方法是獲取一些正則表達式:)盡管...

假設您的年齡采用以下格式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向您顯示您的字符串值(如果找到)。

實際上,您有數據,可以很容易地將其表示為Dictionary<string, string>類型的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"]);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM