Reputation: 125
I currently have a method that reads ints from a file and upon reaching 16 ints a regex is run against the string (register). Although the way the ints (or numbers) are read in from the file is causing me problems. It currently reads all of the numbers from a file and disregards any other chars such as letters. Hence the following would be collected:
Example.txt:
h568fj34fj390fjkkkkf385837692g1234567891011121314fh
Incorrect output:
5683439038583769
Correct output:
1234567891011121
But I only want to collect a string of consecutive numbers (if there are other chars like letters inbetween the numbers they would not be counted) and the method would such for a series of numbers (16 in total) with no other chars like letters inbetween.
My current logic is as follows:
var register = new StringBuilder();
using(var stream = File.Open(readme.txt, FileMode.Open))
{
bool execEnd = false;
bool fileEnded = false;
int buffer;
while(execEnd = true)
{
while(register.Length < 16 && !fileEnded)
{
buffer = stream.ReadByte();
if(buffer == -1)
{
fileEnded = true;
break;
}
var myChar = (char)buffer;
if(Char.IsNumber(myChar))
register.Append(myChar);
}
Upvotes: 0
Views: 238
Reputation: 460158
This should be your required Regex: \d{16}
So you could use LINQ to find all matches:
var allMatches =
System.IO.File.ReadLines(path)
.Select(l => System.Text.RegularExpressions.Regex.Match(l, @"\d{16}"))
.Where(m => m.Success)
.ToList();
foreach (var match in allMatches)
{
String number = match.Value;
}
Upvotes: 4
Reputation: 204766
string input = "h568fj34fj390fjkkkkf385837692g1234567891011121314fh";
string num = System.Text.RegularExpressions.Regex.Match(input, @"\d{16}").Value;
Upvotes: 1