简体   繁体   中英

How can I use indexof and substring to extract numbers from a string and make a List<int> of the numbers?

 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);

The result in results is:

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');

I need to extract each number between ' and ' and add each number to a List

For example: to extract the number 202110071730 and add this number to a List

You can first split by ; to get a list of statements.

Then split each statement by ' to get everything in front of, between and after the ' . Take the middle one ( [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
}

Or, for all the Regex fanboys, '(\d+)' captures a group between ' with some digits:

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
}

RegexStorm

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM