简体   繁体   English

如何从C#中的字符串中获取数字

[英]How to get number from string in C#

i have a String in HTML (1-3 of 3 Trip) how do i get the number 3(before trip) and convert it to int.I want to use it as a count 我有一个HTML格式的字符串(1-3 of 3 Trip)如何获得数字3(在旅行前)并将其转换为int。我想将它用作计数

Found this code 找到这个代码

public static string GetNumberFromStr(string str)
{
  str = str.Trim();
  Match m = Regex.Match(str, @"^[\+\-]?\d*\.?[Ee]?[\+\-]?\d*$");
  return (m.Value);
}

But it can only get 1 number 但它只能获得1个数字

Regex is unnecessary overhead in your case. 在你的情况下,正则表达式是不必要的开销。 try this: 尝试这个:

int ExtractNumber(string input)
{
    int number = Convert.ToInt32(input.Split(' ')[2]);
    return number;
}

Other useful methods for Googlers: Google员工的其他有用方法:

// throws exception if it fails
int i = int.Parse(someString);

// returns false if it fails, returns true and changes `i` if it succeeds
bool b = int.TryParse(someString, out i);

// this one is able to convert any numeric Unicode character to a double. Returns -1 if it fails
double two = char.GetNumericValue('٢')

Forget Regex. 忘记正则表达式。 This code splits the string using a space as a delimiter and gets the number in the index 2 position. 此代码使用空格作为分隔符拆分字符串,并获取索引2位置的数字。

string trip = "1-3 of 3 trip";
string[] array = trip.Split(' ');
int theNumberYouWant = int.Parse(array[2]);

Another way to do it: 另一种方法:

public static int[] GetNumbersFromString(string str)
{
   List<int> result = new List<int>();
   string[] numbers = Regex.Split(input, @"\D+");
   int i;

   foreach (string value in numbers)
   {
      if (int.TryParse(value, out i))
      {
         result.Add(i);
      }
   }

   return result.ToArray();
}

Example of how to use: 如何使用示例:

const string input = "There are 4 numbers in this string: 40, 30, and 10.";
int[] numbers = MyHelperClass.GetNumbersFromString();

for(i = 0; i < numbers.length; i++)
{
    Console.WriteLine("Number {0}: {1}", i + 1, number[i]);
}

Output: 输出:

Number: 4 数量:4

Number: 40 数量:40

Number: 30 人数:30

Number: 10 数量:10

Thanks to: http://www.dotnetperls.com/regex-split-numbers 感谢: http//www.dotnetperls.com/regex-split-numbers

Try this: 尝试这个:

public static int GetNumberFromStr(string str)
{
    str = str.Trim();
    Match m = Regex.Match(str, @"^.*of\s(?<TripCount>\d+)");

    return m.Groups["TripCount"].Length > 0 ? int.Parse(m.Groups["TripCount"].Value) : 0;
}

If I'm reading your question properly, you'll get a string that is a single digit number followed by ' Trip' and you want to get the numeric value out? 如果我正确地阅读你的问题,你会得到一个单个数字后跟'Trip'的字符串,你想得到数值吗?

public static int GetTripNumber(string tripEntry)
{
    return   int.Parse(tripEntry.ToCharArray()[0]);
}

Not really sure if you mean that you always have "(xy of y Trip)" as a part of the string you parse...if you look at the pattern it only catches the "xy" part thought with the acceptance of .Ee+- as seperators. 不确定你是否意味着你总是将“(yy of y trip)”作为你解析的字符串的一部分...如果你看一下这个模式它只能抓住“xy”部分,并接受.Ee + - 作为分隔符。 If you want to catch the "y Trip" part you will have to look at another regex instead. 如果你想要捕捉“y Trip”部分,你将不得不看另一个正则表达式。

You could do a simple, if you change the return type to int instead of string: 如果将返回类型更改为int而不是string,则可以执行一个简单的操作:

Match m = Regex.Match(str, @"(?<maxTrips>\d+)\sTrip");
return m.Groups["maxTrips"].Lenght > 0 ? Convert.ToInt32(m.Groups["maxTrips"].Value) : 0;

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

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