How to check if a string contains only letters, numbers, underscores and dashes in C#

1 Answer

0 votes
using System;
using System.Text.RegularExpressions;

class RegexValidation
{
    public static bool IsValidString(string s) {
        string pattern = "^[A-Za-z0-9_-]*$";
        return Regex.IsMatch(s, pattern);
    }

    static void Main()
    {
        string s1 = "-abc_123-";
        Console.WriteLine(IsValidString(s1) ? "yes" : "no");

        string s2 = "-abc_123-(!)";
        Console.WriteLine(IsValidString(s2) ? "yes" : "no");
    }
}

 
 
/*
run:
 
yes
no
 
*/

 



answered May 31, 2025 by avibootz
...