Prodigga
Prodigga

Reputation: 1477

RegEx to only allow valid Enum member names

I have never used RegEx before, but a need for it arose today.

I need to see whether or not a string passed into my function is a valid Enum member name. Off the top of my head, this means that it cannot contain symbols (other than '_') and cannot start with a letter. Now I can google around and figure that out myself, but I wasn't too sure if those 2 rules were the only rules for enum member names - couldn't find anything online about it.

edit: To add some information... I am writing an editor plug in for unity3d. The user can populate a string list and the script will generate a c# file with those strings as members of the enum. The user can then reference the enum values through the code. The enum generated is basically a list of id's that the user specifies, so in code he can type IdEnum.SomeUserDefinedMember

Upvotes: 1

Views: 3794

Answers (3)

ghord
ghord

Reputation: 13825

Just construct regex for every enumeration type like that:

Type enumeration = ...;
var regex = enumeration.Name + "\.(" + string.Join("|", Enum.GetNames(enumeration)) + ")";

It should match all values of given enum. You could also expand this to match more than one enum type.

Upvotes: 1

Steve B
Steve B

Reputation: 37690

(disclaimer: I never tested such solution, it's only an idea)

To handle all possible values, you may use the C# compiler directly to generate on the fly the enumeration, with your values. If the compilation fails, the enum's value is not valid.

You can try the code of this other SO question :

CodeTypeDeclaration type = new CodeTypeDeclaration("BugTracker");
type.IsEnum = true;

foreach (var valueName in new string[] { "Bugzilla", "Redmine" })
{
  // Creates the enum member
  CodeMemberField f = new CodeMemberField("BugTracker", valueName);


  type.Members.Add(f);
}

OldAnswser, before understanding your requirement :

I don't think using RegEx is the right way.

What you want to do can be coded like this :

enum MyEnum {
    Val1,
    Val2,
    Val3

}

class MyClass {
    void Foo(){
        string someInput = "Val2";

        MyEnum candidate;

        if(Enum.TryParse(someInput, out candidate)){
            // DO something with the enum
            DoSomething(candidate);
        }
        else{
            throw new VeryBadThingsHappened("someInput is not a valid MyEnum");
        }
    }
}

Upvotes: 2

maxlego
maxlego

Reputation: 4914

this regex should ensure valid name for enum value

^[a-zA-Z_][a-zA-Z_0-9]*

Upvotes: 3

Related Questions