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
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('٢')
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]);
:
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; }
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
: 4
: 40
: 30
: 10
: http://www.dotnetperls.com/regex-split-numbers
, , , "Trip", ?
public static int GetTripNumber(string tripEntry) { return int.Parse(tripEntry.ToCharArray()[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;
Source: https://habr.com/ru/post/1780837/More articles:Drag and Drop Canvas in HTML5 - html5https://translate.googleusercontent.com/translate_c?depth=1&pto=aue&rurl=translate.google.com&sl=ru&sp=nmt4&tl=en&u=https://fooobar.com/questions/1780833/slow-calls-to-clojure-proxy&usg=ALkJrhhj5wRh-IYj4reabGrmE1my0knMsgWhat is the point of re-declaring a class interface in an implementation file? - objective-cF # IEvent.create - f #UITextField text alignment in iOS 4.2 - objective-cJava mainframe exchange via JCA error - connection fails - javaProblem with Interop C # / C: AccessViolationException - cMigrating Silverlight MVVM to ASP.NET or ASP.NET MVC Web Forms - c #OOP issue: class extension, function overriding, and jQuery type syntax - oopWorking with axis 2 inside a WAR application - axis2All Articles