Well, the Title pretty much explains my question, but in addition; I am coding in C# for the first time and have limited development experience overall (I am a tester typically)
Mods: I had a look to see if there were any rules about posting a question simply asking for help with a RegEx and could not find anything specific. I attempted to utilize several online regex "generators" but it seems you need to be fairly fluent in order to take advantage of any on offer. I know there are users on here that are absolutely gifted when it comes to formulating strong regular expressions - so here I am posting what seems like a dopey question. Apologies if Ive overlooked something in my frustration.
To all who answer, or attempt to answer - thank you kindly for your time.
Relevant Info:
- I am using this Regex to validate textbox input
- The expression may contain between 1 & 8 alphanumeric characters (including underscores and hyphens), but nothing else.
- Some examples of valid input are "alpha_01", "1234-567", "1337", "A", "123_AbC"
- Examples of invalid input are "$cash", "<test>", "this.one"
- I wish for the text box content to display red in color if the entry is invalid and black if valid.
- I have tried a multitude of expressions that successfully validate in the manner I desire, however all the expressions I have tried also validate undesired characters.
- Expressions I have tried are
(@([[:alnum:]]{1,8}))
(@([\w]{1,8}))
&((@[a-zA-Z0-9_-]{1,8}))
- If I were to limit the text box to 8 characters and use a Regex to disallow entry of undesired characters, I imagine that might suffice for my purposes, but I am not fluent enough in regex to write an expression limiting input in the manner needed.
I doubt it adds anything relevant, but for context here is my current code snippet;
private void textBox1_TextChanged(object sender, EventArgs e)
{
if ((new Regex(**REGEX NEEDEED**).IsMatch(textBox1.Text)))
{
textBox1.ForeColor = Color.Black;
}
else
{
textBox1.ForeColor = Color.Red;
}
}
CodePudding user response:
Does this RegEx work for you?
^[a-zA-Z0-9\-_]{1,8}$
This code:
var inputs = new[] { "alpha_01", "1234-567", "1337", "A", "123_AbC", "$cash", "<test>", "this.one", "muchtoolong" };
var regex = new Regex(@"^[a-zA-Z0-9\-_]{1,8}$");
foreach(var input in inputs)
{
var isMatch = regex.IsMatch(input);
Console.WriteLine(input " " isMatch.ToString());
}
Gives:
alpha_01 True
1234-567 True
1337 True
A True
123_AbC True
$cash False
<test> False
this.one False
muchtoolong False