簡體   English   中英

從字符串中獲取數字

[英]Get the Number from a string

我想修剪字符串並獲取特殊字符之間的數字。 例如,有一個string BC/PO/88/2018我想得到88。

您可以使用正則表達式:

string strRegex = @"[A-Z]{2}/[A-Z]{2}/(?<MyNumber>[0-9]*)/[0-9]{4}";
Regex myRegex = new Regex(strRegex, RegexOptions.None);
string strTargetString = @"BC/PO/88/2018";

foreach (Match myMatch in myRegex.Matches(strTargetString))
{
  if (myMatch.Success)
  {
    // Add your code here
  }
}

您可以使用正則表達式並提取數字

Match match = Regex.Match("BC/PO/88/2018 f" , @"(\d+)");
if (match.Success) {
   return int.Parse(match.Groups[0].Value);
}

另一種方法是,如果您確定將字符串作為輸入,即確定字符串的格式,則可以按照注釋中的建議在String.Split的幫助下進行String.Split

暫無
暫無

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

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