Feedback

kontrolliert ob String eine gültige GUID ist

Sprache: C#

Diese Methode kontrolliert mittels Regex ob der übergebene String eine Guid ist. benötigte Namespaces: System.Text.RegularExpressions
/// <summary>
/// Determines whether the specified candidate is a valid GUID.
/// </summary>
/// <param name="candidate">The candidate.</param>
/// <returns>
/// 	<c>true</c> if the specified candidate is GUID; otherwise, <c>false</c>.
/// </returns>
public static bool IsValidGuid(string candidate)
{
    if (string.IsNullOrEmpty(candidate))
        return false;

    Regex isGuid = new Regex(@"^({){0,1}[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}(}){0,1}$");
    return isGuid.IsMatch(candidate);
}
/// <summary>
/// Determines whether the specified candidate is a valid GUID.
/// </summary>
/// <param name="candidate">The candidate.</param>
/// <returns>
/// 	<c>true</c> if the specified candidate is GUID; otherwise, <c>false</c>.
/// </returns>
public static bool IsValidGuid(string candidate)
{
    if (string.IsNullOrEmpty(candidate))
        return false;

    Regex isGuid = new Regex(@"^({){0,1}[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}(}){0,1}$");
    return isGuid.IsMatch(candidate);
}

4 Kommentare

  1. Gute Frage, damals war ich ja noch nicht wirklich dabei. In der MSDN existiert nur eine Doku zu .NET 4.0 zu den genannten Methoden, also vermutlich nicht.
    Ich hätte echt gedacht das alle Strukturen (bei denen es Sinn macht) die Parse/TryParse-Methoden besitzen…naja, bis .NET 3.5 dürfte Regex als Lösung nicht so schlecht sein.

  2. Ich weiß es auch nicht, ob es damals schon Guid.TryParse gab. Damals war ich wohl verliebt in Regex und habe alles mögliche damit validiert. Ich mag Regex immer noch gern 🙂