比较C#中的字符串和静态正则表达式?

Jen*_*all 1 c# regex string

我想知道,对于那些真正不熟悉正则表达式的人来说,找到如何将字符串与指定字符串的正则表达式格式匹配,有什么简单的方法吗?

例如,这个字符串是从另一个函数生成的,我有:

3A5AE0F4-EB22-434E-80C2-273E315CD1B0

我不知道这个字符串的正确正则表达式是什么.

假设我有一个函数将此字符串作为参数

        public static bool isValidRegex(string inputString)
        {
            Regex myRegex = ????

            if inputstring matches myRegex then
            return true;

            else 
            return false;


        }
Run Code Online (Sandbox Code Playgroud)

正则表达式将使此函数返回true是什么?

注意:由于我不熟悉C#,所提供的代码可能根本不正确,我知道.

Jon*_*eet 9

在这种情况下,看起来这是一个Guid - 如果你使用的是.NET 4,最简单的方法可能就是使用Guid.TryParse...但如果你需要使用正则表达式,它可能是:

^[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}$
Run Code Online (Sandbox Code Playgroud)

换句话说,字符串的开头,8个十六进制数字,短划线,4个十六进制数字,短划线,4个十六进制数字,短划线,4个十六进制数字,短划线,12个十六进制数字,字符串结尾.请注意,我假设任何字母字符都是大写而不是低级.

它可能值得创建一次,并可能编译它,所以你最终得到:

private static readonly Regex GuidPattern = new Regex
    ("^[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}$",
      RegexOptions.Compiled);

public static bool IsValidRegex(string inputString)
{
    return GuidPattern.IsMatch(inputString);
}
Run Code Online (Sandbox Code Playgroud)