简体   繁体   English

从字符串中获取数字

[英]Get the Number from a string

I want to trim a string and get the number between special characters. 我想修剪字符串并获取特殊字符之间的数字。 For example there is a string BC/PO/88/2018 from it i want to get 88. 例如,有一个string BC/PO/88/2018我想得到88。

You could use Regular Expressions: 您可以使用正则表达式:

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

you can make use of regular expression and extract number 您可以使用正则表达式并提取数字

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

other way is you can do with the help of String.Split as suggested in comments if you are sure about string coming as input ie sure about format of string. 另一种方法是,如果您确定将字符串作为输入,即确定字符串的格式,则可以按照注释中的建议在String.Split的帮助下进行String.Split

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM