0

I am trying to future proof a program I am creating so that the pattern I need to have users put in is not hard coded. There is always a chance that the letter or number patter can change, but when it does I need everyone to remain consistent. Plus I want the managers to be to control what goes in without relying on me. Is it possible to use regex or another string tool to compare input against a list stored in a database. I want it to be easy so the patterns stored in the database would look like X###### or X######-X####### and so on.

2
  • 1
    You can probably use Masks (sort of regexes) instead of real regexes: see msdn.microsoft.com/en-us/library/… These can be used in textboxes to allow users to only enter valid text.
    – Davio
    Jul 1, 2014 at 17:46
  • Is it WPF or Win Form? Please add more specifics to your requirement. Rgds, Jul 1, 2014 at 17:47

4 Answers 4

0

Sure, just store the regular expression rules in a string column in a table and then load them into an IEnumerable<Regex> in your app. Then, a match is simply if ANY of those rules match. Beware that conflicting rules could be prone to greedy race (first one to be checked wins) so you'd have to be careful there. Also be aware that there are many optimizations that you could perform beyond my example, which is designed to be simple.

List<string> regexStrings = db.GetRegexStrings();
var result = new List<Regex>(regexStrings.Count);
foreach (var regexString in regexStrings)
{
    result.Add(new Regex(regexString);
}

...

// The check
bool matched = result.Any(i => i.IsMatch(testInput));
3
  • This example does work, but how do I get it to work more dynamic. It comes back true if the input is X### and the database has X###. What I want though is for X### to be true against X123, but false against X1234. That type of comparison.
    – Jeebwise
    Jul 1, 2014 at 18:01
  • Also, I was hoping for the database to actually hold "X###". I know that in excel you can create custom fields like this
    – Jeebwise
    Jul 1, 2014 at 18:02
  • You'd use Regex constraints... There are ways to limit match inputs. You'd need to do some Googling to learn about the ways to limit Regex input.
    – Haney
    Jul 1, 2014 at 18:20
0

You could store your patterns as-is in your database, and then translate them to regexes.

I don't know specifically what characters you'd need in your format, but let's suppose you just want to substitute a number to # and leave the rest as-is, here's some code for that:

public static Regex ConvertToRegex(string pattern)
{
    var sb = new StringBuilder();

    sb.Append("^");

    foreach (var c in pattern)
    {
        switch (c)
        {
            case '#':
                sb.Append(@"\d");
                break;

            default:
                sb.Append(Regex.Escape(c.ToString()));
                break;
        }
    }

    sb.Append("$");

    return new Regex(sb.ToString());
}

You can also use options like RegexOptions.IgnoreCase if that's what you need.

NB: For some reason, Regex.Escape escapes the # character, even though it's not special... So I just went for the character-by-character approach.

0
        private bool TestMethod()
{
    const string textPattern = "X###";
    string text = textBox1.Text;
    bool match = true;

    if (text.Length == textPattern.Length)
    {
        char[] chrStr = text.ToCharArray();
        char[] chrPattern = textPattern.ToCharArray();
        int length = text.Length;

        for (int i = 0; i < length; i++)
        {
            if (chrPattern[i] != '#')
            {
                if (chrPattern[i] != chrStr[i])
                {
                    return false;
                }
            }
        }
    }
    else
    {
        return false;
    }
    return match;
}

This is doing everything I need it to do now. Thanks for all the tips though. I will have to look into the regex more in the future.

0

Using MaskedTextProvider, you could do do something like this:

using System.Globalization;
using System.ComponentModel;
string pattern = "X&&&&&&-X&&&&&&&";
string text = "Xabcdef-Xasdfghi";

var culture = CultureInfo.GetCultureInfo("sv-SE");
var matcher = new MaskedTextProvider(pattern, culture);
int position;
MaskedTextResultHint hint;
if (!matcher.Set(text, out position, out hint))
{
    Console.WriteLine("Error at {0}: {1}", position, hint);
}
else if (!matcher.MaskCompleted)
{
    Console.WriteLine("Not enough characters");
}
else if (matcher.ToString() != text)
{
    Console.WriteLine("Missing literals");
}
else
{
    Console.WriteLine("OK");
}

For a description of the format, see: http://msdn.microsoft.com/en-us/library/system.windows.forms.maskedtextbox.mask

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.