C # Regular string expression and Guid validation

1

(1). I would like to validate a string, checking if it has only {a-z], [A-Z], [0-9], '-'}

if(minhaString.ContemApenas({[a-z], [A-Z], [0-9], '-'}) == true)
{
   // Minha string é válida!
}


(2). I need to also validate if such a string is a Guid.

if(minhaString == Guid){
  // String é um Guid Válido!
}
    
asked by anonymous 23.09.2015 / 21:38

2 answers

2

It's pretty easy to do both, see:

using System;
using System.Text.RegularExpressions;
using static System.Console;

public class Program
{
    public static void Main()
    {
        string str = "palavra1-2-3";
        Regex rgx = new Regex(@"^[a-zA-Z0-9-]+$");

        bool isValid = rgx.IsMatch(str);

        WriteLine(isValid);

        //Para verificar se a string é uma Guid

        Guid result;
        bool isGuid = Guid.TryParse(str, out result);

        WriteLine(isGuid);
    }
}

See working in dotNetFiddle
Documentation Guid.TryParse()

    
23.09.2015 / 21:55
2
  

I would like to validate a string, checking if it has only {a-z], [A-Z], [0-9], '-'}

It can be done like this:

var re = new Regex("[A-Za-z0-9\-]+");
var valido = re.Match("Minha String 1-2-3").Success;
  

I also need to validate if that string is a Guid

The fastest way is this:

var guidValido = PInvoke.ObjBase.CLSIDFromString(meuGuid, out valor) >= 0;
    
23.09.2015 / 21:54