需求:從 "p27p p34p" 等字串中提取所有數字(如 27、34),存入陣列供後續查詢使用。最簡潔的做法是使用 Regex.Matches 配合 LINQ。
using System.Text.RegularExpressions;
using System.Linq;
string input = "p27p p34p p100p";
// 提取所有連續數字
int[] ids = Regex.Matches(input, @"\d+")
.Cast<Match>()
.Select(m => int.Parse(m.Value))
.ToArray();
// 結果:[27, 34, 100]
// 僅提取 "p" 包圍的數字
int[] ids = Regex.Matches(input, @"(?<=p)\d+(?=p)")
.Cast<Match>()
.Select(m => int.Parse(m.Value))
.ToArray();
List<int> list = new List<int>();
foreach (Match m in Regex.Matches(input, @"\d+")) {
list.Add(int.Parse(m.Value));
}
int[] ids = list.ToArray();
Regex.Matches 即可,避免手寫循環 IndexOf/Substring 易出錯且效能低。Regex 實例靜態化並加 RegexOptions.Compiled:static readonly Regex NumRegex = new Regex(@"\d+", RegexOptions.Compiled);此法簡潔、可讀、效能佳,適用於 .NET Core / .NET 5+ 及舊版 Framework。