Hello guys in my desktop application i want create regex pattern to allow user to insert only LETTRRS
, NUMBERS
and _ -.
.
Example:
Company name can contain only this characters:
What i try:
string companyName = "My Company #%";
if(Regex.IsMatch(companyName, @"^[a-zA-Z0-9_.-]+$"))
{
MessageBox.Show("Company name contain invalid characteds");
}
else
{
// success
}
But this not working.
I just need that user can only input:
Letters, Numbers, Dot, Underscore line, -
and speca between words all other specific character not alowed in name.
Does i have mistake in regex pattern?
You forgot to include the whitespace character. And as mentioned in the comments your logic is reversed:
if (Regex.IsMatch(companyName, @"^([a-zA-Z0-9_.-]|\s)+$"))
{
Console.WriteLine("Valid");
}
else
{
Console.WriteLine("Company name contains invalid characters");
}
As pointed out in the comments by Wiktor Stribiżew, your logic states that when have a valid pattern
if(Regex.IsMatch(companyName, @"^[a-zA-Z0-9_.-]+$"))
Then show:
MessageBox.Show("Company name contain invalid characteds");
Which should be the other way around.
You could use the dot and hyphen as a separator in a character class [-.]
in a repeating pattern.
If you place them as the first part, they will not match at the start and at the end.
Then you can use another repeating pattern using the same logic as the first part, this time preceded by a space.
^[a-zA-Z0-9_]+(?:[-.][a-zA-Z0-9_]+)*(?: [a-zA-Z0-9_]+(?:[-.][a-zA-Z0-9_]+)*)*$
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.