[英]How to get number from string in C#
我有一個HTML格式的字符串(1-3 of 3 Trip)如何獲得數字3(在旅行前)並將其轉換為int。我想將它用作計數
找到這個代碼
public static string GetNumberFromStr(string str)
{
str = str.Trim();
Match m = Regex.Match(str, @"^[\+\-]?\d*\.?[Ee]?[\+\-]?\d*$");
return (m.Value);
}
但它只能獲得1個數字
在你的情況下,正則表達式是不必要的開銷。 嘗試這個:
int ExtractNumber(string input)
{
int number = Convert.ToInt32(input.Split(' ')[2]);
return number;
}
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('٢')
忘記正則表達式。 此代碼使用空格作為分隔符拆分字符串,並獲取索引2位置的數字。
string trip = "1-3 of 3 trip";
string[] array = trip.Split(' ');
int theNumberYouWant = int.Parse(array[2]);
另一種方法:
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
嘗試這個:
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;
}
如果我正確地閱讀你的問題,你會得到一個單個數字后跟'Trip'的字符串,你想得到數值嗎?
public static int GetTripNumber(string tripEntry)
{
return int.Parse(tripEntry.ToCharArray()[0]);
}
不確定你是否意味着你總是將“(yy of y trip)”作為你解析的字符串的一部分...如果你看一下這個模式它只能抓住“xy”部分,並接受.Ee + - 作為分隔符。 如果你想要捕捉“y Trip”部分,你將不得不看另一個正則表達式。
如果將返回類型更改為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.