首页 > 解决方案 > 如何使用 indexof 和 substring 从字符串中提取数字并制作列表的数字?

问题描述

 var file = File.ReadAllText(@"D:\localfile.html");

                int idx = file.IndexOf("something");
                int idx1 = file.IndexOf("</script>", idx);

                string results = file.Substring(idx, idx1 - idx);

结果的结果是:

arrayImageTimes.push('202110071730');arrayImageTimes.push('202110071745');arrayImageTimes.push('202110071800');arrayImageTimes.push('202110071815');arrayImageTimes.push('202110071830');arrayImageTimes.push('202110071845');arrayImageTimes.push('202110071900');arrayImageTimes.push('202110071915');arrayImageTimes.push('202110071930');arrayImageTimes.push('202110071945');

我需要提取'和'之间的每个数字并将每个数字添加到列表中

例如:提取号码 202110071730 并将此号码添加到 List

标签: c#winforms

解决方案


您可以首先拆分;以获取语句列表。

然后将每个语句拆分'以获取 . 之前、之间和之后的所有内容'。取中间的([1])。

string s = "arrayImageTimes.push('202110071730');arrayImageTimes.push('202110071745');arrayImageTimes.push('202110071800');arrayImageTimes.push('202110071815');arrayImageTimes.push('202110071830');arrayImageTimes.push('202110071845');arrayImageTimes.push('202110071900');arrayImageTimes.push('202110071915');arrayImageTimes.push('202110071930');arrayImageTimes.push('202110071945');";
var statements = s.Split(new string[] { ";" }, StringSplitOptions.RemoveEmptyEntries);
foreach (var statement in statements)
{
    Console.WriteLine(statement.Split('\'')[1]); // add to a list instead
}

或者,对于所有的 Regex 粉丝,用一些数字'(\d+)'捕获一个组:'

Regex r= new Regex("'(\\d+)'");
var matches = r.Matches(s);
foreach (Match match in matches)
{
    Console.WriteLine(match.Groups[1].Value);  // add to a list instead
}

正则表达式风暴


推荐阅读