My code is parsing a text file, looking for ID numbers that match the pattern "####-####-#". Once I find a number that matches this pattern, I need to strip out the dashes and store it in a string variable. I'm trying to use String.Remove to remove this character, but keep getting the OutOfRangeException for some reason.
Here's my code:
//regex for the ID number pattern
Regex pattern = new Regex("^[0-9]{4}-[0-9]{4}-[0-9]{1}$");
//StreamReader to iterate thru the file line-by-line
using (StreamReader reader = new StreamReader(pathToMyFile))
{
while (!reader.EndOfStream)
{
readLine = reader.ReadLine();
//the number I want is always at the beginning of the line, so I capture the
//first 11 characters for regex comparison
string possibleMatch = readLine.Substring(0, 11);
if (!String.IsNullOrEmpty(possibleMatch) &&
pattern.Match(possibleMatch).Success)
{
//If possibleMatch isn't blank, and matches the regex, we found an ID
string match = possibleMatch.Remove('-');
}
}
}
When I try to remove the dashes, I get this error:
System.ArgumentOutOfRangeException: 'startIndex must be less than length of string.
Parameter name: startIndex'
The error is always thrown on the possibleMatch.Remove('-')
method, never on readLine.Substring(0, 11)
. Any advice is appreciated.