如何使用IndexOf和Substring从字符串提取数字并生成List<int>集合
实现方案
你可以通过正则匹配或者字符串分割两种方式提取目标数字,以下是具体实现代码:
方法1:正则匹配(推荐,兼容性强)
首先引用命名空间:using System.Text.RegularExpressions;
基础写法:
List<int> imageTimeList = new List<int>(); Regex numRegex = new Regex(@"'(\d+)'"); MatchCollection matchResult = numRegex.Matches(results); foreach (Match item in matchResult) { if (int.TryParse(item.Groups[1].Value, out int timeVal)) { imageTimeList.Add(timeVal); } }
如果偏好LINQ的简洁写法,可以用如下代码:
using System.Linq; using System.Text.RegularExpressions; List<int> imageTimeList = Regex.Matches(results, @"'(\d+)'") .Cast<Match>() .Select(m => int.TryParse(m.Groups[1].Value, out int val) ? val : 0) .Where(val => val != 0) .ToList();
方法2:字符串分割(无需引入正则命名空间)
利用单引号分割字符串后,奇数下标的元素就是我们要提取的数字内容:
List<int> imageTimeList = new List<int>(); string[] splitArr = results.Split('\''); // 从索引1开始,步长为2遍历即可拿到所有单引号包裹的内容 for (int i = 1; i < splitArr.Length; i += 2) { if (int.TryParse(splitArr[i], out int timeVal)) { imageTimeList.Add(timeVal); } }
注意事项
你提取的12位时间戳数值约为2000亿,已经超出C# int类型的最大值(2147483647),直接转换会失败。如果出现转换无结果的情况,建议将集合类型改为List<long>,对应使用long.TryParse做转换即可。
内容的提问来源于stack exchange,提问作者Daniel Lip
相关产品推荐
相关产品推荐

