Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8172911
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 6, 20262026-06-06T21:56:24+00:00 2026-06-06T21:56:24+00:00

I have a C# regex-parser program with three files in it, each containing a

  • 0

I have a C# regex-parser program with three files in it, each containing a static class:

1) one static class filled with string dictionaries

static class MyStringDicts
{
    internal static readonly Dictionary<string, string> USstates =
        new Dictionary<string, string>()
        {
            { "ALABAMA", "AL" },
            { "ALASKA", "AK" },
            { "AMERICAN SAMOA", "AS" },
            { "ARIZONA", "AZ" },
            { "ARKANSAS", "AR" }
             // and so on
        }
    // and some other dictionaries
}

2) A class that compiles these values into Regex

public static class Patterns
{       
    Public static readonly string StateUS =
        @"\b(?<STATE>" + CharTree.GenerateRegex(Enumerable.Union(
            AddrVals.USstates.Keys,
            AddrVals.USstates.Values))
        + @")\b";

    //and some more like these
}

3) some code that runs regular expressions based on these strings:

public static class Parser
{   
    // heavily simplified example
    public static GroupCollection SearchStringForStates(string str)
    {
        return Regex.Match(str, 
            "^" + Patterns.StateUS, 
            RegexOptions.ExplicitCapture | RegexOptions.IgnoreCase).Groups;
    }
}

I’d like to be able to generate 2) as with a T4 template, as all of this concatenation is identical on every execution:

@"\b(?<STATE><#=CharTree.GenerateRegex(Enumerable.Union(
    AddrVals.USstates.Keys,
    AddrVals.USstates.Values)#>)\b";

This works, but if I create a new member of MyStringDicts, or add/remove some values from its dictionaries, the T4 template won’t recognize them until exclude Patterns.cs from compilation and recompile. As Parser depends on Patterns, this really isn’t an option – I need the T4 transformation to take into account changes to other files in the same build.

Things I don’t want do do:

  • Split MyStringDicts into its own project. I’d like to keep the files in one project, as they are a logical unit.
  • Just move MyStringDicts into the top of Patterns.cs. I need the MyStringDicts members for other purposes, too (for dictionary lookups, or in other T4 templates, for example.)

I adopted the advice here about using T4Toolbox’s VolatileAssembly and such, but that seems to only work for the reverse direction, when the class files need to be recompiled after editing the T4 template.

Is what I want possible?

edited for clarity

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-06T21:56:27+00:00Added an answer on June 6, 2026 at 9:56 pm

    I just created a small test template which uses EnvDte (Visual Studio Automation) and the T4Toolbox to run through the first file. It picks up the file through the project, so there’s no need to compile before running the template. In fact, it even picks up unsaved changes…

    This is basically the same approach as FullSnabel uses, but without the need for Roslyn.

    <#@ template debug="false" hostspecific="True" language="C#" #>
    <#@ output extension=".cs" #>
    <#@ Assembly Name="System.Core.dll" #>
    <#@ dte processor="T4Toolbox.DteProcessor" #>
    <#@ TransformationContext processor="T4Toolbox.TransformationContextProcessor" #>
    <#@ assembly name="System.Xml" #>
    <#@ assembly name="EnvDTE" #>
    <#@ assembly name="EnvDTE80" #>
    <#@ import namespace="T4Toolbox" #>
    <#@ import namespace="EnvDTE" #> 
    <#@ import namespace="EnvDTE80" #>
    <#
        ProjectItem projectItem = TransformationContext.FindProjectItem("Dictionaries.cs");
        FileCodeModel codeModel = projectItem.FileCodeModel;
    
        foreach (CodeElement element in codeModel.CodeElements)
        {
            CodeNamespace ns = element as CodeNamespace;
            if(ns != null)
            {
                foreach(CodeElement ele in ns.Children)
                {
                    CodeClass cl = ele as CodeClass;
    
                    if(cl != null && cl.Name == "Dictionaries")
                    {
                        foreach(CodeElement member in cl.Members)
                        {
                            // Generate stuff...
                            this.WriteLine(member.Name);
                        }
                    }
                }
            }
        }
    #>
    

    This should work if you want to stick to your original approach.

    What you seem to be doing is storing data in a class file. You could consider storing your lists outside code (in an xml or ini file) and generate both files based on that data. That way you avoid the problem all together, it might also make managing the lists easier.
    If you don’t care too much about changes to the list you could also put the dictionaries inside the T4 template itself.

    Another alternative might dealing with it fully in code. You could create a subclass of Dictionary which has a ‘Pattern’ property (or GetPattern() function). The parser would then use AddrVals.USstates.Pattern, and the patterns class won’t be needed anymore. This way you won’t need any code generation.

    Perhaps a wrapper around the actual dictionary would be better because it allows you to hide the actual collection to make sure it’s not changed at runtime. See Is there a read-only generic dictionary available in .NET? for an example of that.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a program in C# WPF which analyzes certain log files. Each log
I have a string: [\n['-','some text what\rcontains\nnewlines'],\n\n trying to parse: Regex.Split(@[\n['-','some text what contains
I have some Regex, it looks like this: string regexForDrop = @^((%27)|'|(\-\-))\s*(d|%64|%44)(r|%72|%52)(o|%6F|%4F)(p|%70|%50)$; It works
I have a Perl program that stores regular expressions in configuration files. They are
I have a string that I have parsed from XML using Google's GDataXML parser,
To outline: I have a parser that grabs Cell references using the following regex
I have the following method in some nemerle code: private static getLinks(text : string)
I have a string that I want to parse using regex. It has the
I have regex patterns in PHP $s = preg_replace(#\[URL\=(.*)\](.*)\[\/URL\]#Ui, <a href=\$1\ target=\_blank\>$2</a>, $s); $s
I have a regex I'm running to filter rows in a table. The filtering

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.