Home > OS >  How can I use indexof and substring to extract numbers from a string and make a List<int> of t
How can I use indexof and substring to extract numbers from a string and make a List<int> of t

Time:10-08

 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

CodePudding user response:

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

  • Related