I am trying to read in a text file which has this format below, into an array:
Previous errors were for Test id \'1234567\' Error id \'12345678\'
Previous errors
Use Regex.Split() if you want the text use
string pattern = @"\d+";
if you want the numbers use:
pattern = "[a-z]+";
then
string[] extracted = Regex.Split(sr.Readline(), pattern, RegexOptions.IgnoreCase);
Since you already have an array with all the lines of text in, you could just iterate over them, and read out the numbers from each.
One such solution:
// Extention method to simplify:
public static string GetNumbersFromPos(this string line, int nrToSkip)
{
return new string(line.Skip(nrToSkip)
.TakeWhile(c => Char.IsNumber(c))
.ToArray());
}
// Assume you get this from your array:
var eachLine = "Previous errors were for Test id '1234567' Error id '12345678'";
// Find nr of chars to skip
var beforeFirstId = eachLine.IndexOf("id '") + 4;
var beforeSecondId = eachLine.IndexOf("id '", beforeFirstId) + 4;
// Now use the extention method to get the two number-strings:
var firstId = eachLine.GetNumbersFromPos(beforeFirstId);
var secondId = eachLine.GetNumbersFromPos(beforeSecondId);
This will give you the numbers as strings in firstId
and secondId
, which you can then store, or parse to int, or whatever you need.
A very basic solution is read the lines, split them and find valid integers:
List<int> test = new List<int>();
List<int> error = new List<int>();
using (var reader = new StreamReader(@"D:\Temp\AccessEmail.txt")){
string line;
while ((line = reader.ReadLine()) != null){
//split the line
string[] parts = line.Split(new[]{"Error"}, StringSplitOptions.None);
//get valid integers
test.Add(GetInt(parts[0].Split(' ', '\'')));
error.Add(GetInt(parts[1].Split(' ', '\'')));
}
}
//print the number of elements in the lists
Console.WriteLine(test.Count);
Console.WriteLine(error.Count);
int GetInt(string[] a){
int i = 0;
foreach (string s in a)
int.TryParse(s, out i);
return i;
}