[Solved] Make “automatic” corrections on failed groups matching


You can do it using a replacement map, replacing the character at index 1 if the given code doesn’t start with two letters:

using System;
using System.Text;
using System.Collections.Generic;
using System.Text.RegularExpressions;

public class Test
{
    private static string[] productCodes = new[] { 
        "MD0133776311I",
        "M10133776311I",
        "M20133776311I"
    };

    private static Dictionary<char, char> replacementMap = new Dictionary<char, char> {
        { '1', 'I' },
        { '2', 'S' },
    };

    private static Regex startsWithTwoLettersRegex = new Regex("^([A-Z]{2})");

    public static void Main()
    {
        foreach (var code in productCodes)
        {
            Console.Write("{0} -> ", code);
            if (!startsWithTwoLettersRegex.Match(code).Success)
            {
                Console.WriteLine(FixProductCode(code));
            }
            else
            {
                Console.WriteLine("OK!");   
            }
        }
    }

    static string FixProductCode(string code)
    {
        StringBuilder sb = new StringBuilder(code);
        sb[1] = replacementMap[code[1]];
        return sb.ToString();
    }
}

Outputs:

MD0133776311I -> OK!
M10133776311I -> MI0133776311I
M20133776311I -> MS0133776311I

See example on IdeOne.

I’m sure you can mold this into something more flexible, but like I said in my comments, a regex can’t guess what you mean. You need to be explicit in code, and manually fixing characters at set positions in the string.

Note this won’t fix the first character if that isn’t a letter, nor will it check the remainder of the code.

solved Make “automatic” corrections on failed groups matching