Click here to Skip to main content
12,451,425 members (50,066 online)
Click here to Skip to main content

Stats

21.4K views
44 downloads
12 bookmarked
Posted

Create Regex Objects using a Kind of "meta-variables" - Quicker and Easier

, 10 Jan 2007 CPOL
This article describes a class VarRegex allowing you to reuse parts of regular expressions
using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;

/*
 * VarRegex sample program
 * (C) Eugene MIrotin aka Guard, 2007
 */

namespace varRegex
{
    class Program
    {
        static void Main(string[] args)
        {
            VarRegex vr = new VarRegex();
            vr.Variables["int"] = @"\d+";
            vr.Variables["i"] = @"`int`";
            vr.Variables["sep"] = @"[\s\-]";
            vr.Variables["gr"] = @"`i``sep`";
            vr.Pattern = @"`gr`*`i`";
            vr.Options = RegexOptions.IgnoreCase;

            string str = @"123 568-99";
            Match m = vr.Regex.Match(str);
            Console.WriteLine("Result for string {1}: {0}\n", m.Success, str);

            Console.WriteLine("Variables:\n");
            foreach (String s in vr.Variables)
                Console.WriteLine(s + "\n");

            Console.WriteLine("\nExpanded Variables:\n");
            foreach (String s in vr.Variables.ExpandedVariables)
                Console.WriteLine(s + "\n");

            vr.Variables["int"] = @"\D";
            m = vr.Regex.Match(str);
            Console.WriteLine("Result for string {1}: {0}\n", m.Success, str);

        }
    }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Eugene Mirotin (Guard)
Software Developer
Belarus Belarus
No Biography provided

You may also be interested in...

| Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.160826.1 | Last Updated 10 Jan 2007
Article Copyright 2007 by Eugene Mirotin (Guard)
Everything else Copyright © CodeProject, 1999-2016
Layout: fixed | fluid