諮詢區
-
van:
我現在有一個需求,想從 string 中找到所有的 number 並提取出來。
舉例如下:
string test = "1 hello"
string test1 = " 1 world"
string test2 = "helloworld 99"
請問我該如何做?
回答區
-
Tabares:
這個簡單,可以用正則表達式 Regex.Split
提取所有的 number,使用下面的代碼。
public class Program
{
static void Main(string[] args)
{
string input = "There are 4 numbers in this string: 40, 30, and 10.";
// Split on one or more non-digit characters.
string[] numbers = Regex.Split(input, @"\D+");
foreach (string value in numbers)
{
if (!string.IsNullOrEmpty(value))
{
int i = int.Parse(value);
Console.WriteLine("Number: {0}", i);
}
}
}
}
-
Ramireddy Ambati:
可以試着用 Regex.Matches
提取。
static void Main(string[] args)
{
string input = "Hello 20, I am 30 and he is 40";
var numbers = Regex.Matches(input, @"\d+").OfType<Match>().Select(m => int.Parse(m.Value)).ToArray();
foreach (var item in numbers)
{
Console.WriteLine($"number: {item}");
}
}
-
Thomas C. G. de Vilhena:
我寫了一個擴展方法可以提取出 string 中所有的正整數,方法如下:
public static class StringExt
{
public static List<long> Numbers(this string str)
{
var nums = new List<long>();
var start = -1;
for (int i = 0; i < str.Length; i++)
{
if (start < 0 && Char.IsDigit(str[i]))
{
start = i;
}
else if (start >= 0 && !Char.IsDigit(str[i]))
{
nums.Add(long.Parse(str.Substring(start, i - start)));
start = -1;
}
}
if (start >= 0)
nums.Add(long.Parse(str.Substring(start, str.Length - start)));
return nums;
}
}
然後像下面這樣調用
public static void Main(string[] args)
{
var input = "I was born in 1989, 27 years ago from now (2016)";
foreach (var item in input.Numbers())
{
Console.WriteLine($"number: {item}");
}
}
點評區
從解答中再次看到了 正則
的強大威力,不得不服,不過這種需求可以簡單,也可以特別複雜,比如考慮下面的情況:
-
小數 eg: 200.002,100.01 -
負數 eg: -20.02,-10.0
當然都可以用相對複雜的正則寫出來,但現實中不得不考慮這些情況哈😂😂😂
原文鏈接:https://stackoverflow.com/questions/4734116/find-and-extract-a-number-from-a-string
本文分享自微信公衆號 - 一線碼農聊技術(dotnetfly)。
如有侵權,請聯繫 [email protected] 刪除。
本文參與“OSC源創計劃”,歡迎正在閱讀的你也加入,一起分享。