How to get a number from a string in C #

I have a line in HTML (1-3 of 3 Trip), how can I get number 3 (before the trip) and convert it to int.I want to use it as a counter

Found this code

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

But he can only get 1 number

+3
source share
6 answers

Regex is the extra overhead in your case. try the following:

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

Other useful methods for googlers:

// 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('٢')
+12
source

Forget the regex. This code breaks the line, using a space as a separator, and gets the number at index position 2.

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

:

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;
}
+1

:

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

:

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

:

: 4

: 40

: 30

: 10

: http://www.dotnetperls.com/regex-split-numbers

+1

, , , "Trip", ?

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

, , "(xy of y Trip)", , ... , "xy", .Ee + - . "y Trip", .

, int :

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

Source: https://habr.com/ru/post/1780837/


All Articles