jonathan
jonathan

Reputation: 11

C# How to use textbox text as Regex OR String

I have an application that the user may specify a prompt... That may be in Regex type or in string type.

The user have a checkbox, if he check the checkbox the prompt var will be a string type if not check will be a Regex.

Then I need to be able to reference that later in the program.

so I am wondering how to define that...

Currently I have the following :

textbox1.text = "\[.*@.*\][\$|\#]"  < --- that is a Regex 

or it could be something like :

textbox1.text = "#$"                < --- that would be a regular string...

and somewhere in my apps I need to use that info...

string userPrompt:
string rootPrompt;

if (userPromptIsText)
{
    userPrompt = textBoxp4RegPrompt.Text.Trim();
}
else
{
    // here how do I say that userprompt is a regex type?
} 

Upvotes: 0

Views: 925

Answers (1)

James Toomey
James Toomey

Reputation: 6082

It seems like you should store the entered regular expression not in the string variable "userPrompt", but rather in a Regex so you can use it:

System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex(textBoxp4RegPrompt.Text.Trim());

And then you can use the regex variable for performing matches:

System.Text.RegularExpressions.Match results = regex.Match(stringToTest);  
MessageBox.Show(results.Groups[0].Value);
MessageBox.Show(results.Groups[1].Value); 

Upvotes: 1

Related Questions