C# Regular expression for string and Guid validation

Asked

Viewed 777 times

1

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

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


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

if(minhaString == Guid){
  // String é um Guid Válido!
}
  • You have the regex ready and does not know how to apply, this?

  • In fact, I think there should be two separate questions.

  • I don’t have Regex, I’d like to learn how to ride it. ContemApenas() was just an example. I asked the same question because they are validations for the same object.

  • 1

    I recommend reading http://answall.com/questions/42459/express%C3%A3o-regular-n%C3%A3o-works-correctly-in-webform/42486

2 answers

2

I would like to validate a string by checking that it only has {[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 such a string is a Guid

The fastest way is like this:

var guidValido = PInvoke.ObjBase.CLSIDFromString(meuGuid, out valor) >= 0;

2


It’s very 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 on dotNetFiddle
Documentation Guid.TryParse()

Browser other questions tagged

You are not signed in. Login or sign up in order to post.