0

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.

bmurrell30
  • 565
  • 8
  • 23
  • 2
    Your `'-'` is being implicitly converted to `int` because there is no overload of `string.Remove` that takes a `char`, but there is one that takes an `int`. See the [documentation on the string.Remove overloads](https://learn.microsoft.com/en-us/dotnet/api/system.string.remove?view=net-5.0). – Joe Sewell Jul 21 '21 at 21:02
  • Yes, string.Remove doesn't work in that way. You need to use string.Replace – Steve Jul 21 '21 at 21:06
  • String.Replace it is. Gotta love lessons in humility. – bmurrell30 Jul 21 '21 at 21:34

0 Answers0