Questions about using Contains with Regex in C #

2

I would like to use the Contains method in a code in C #, but instead of passing a string literal, that is, a specific word, pass a pattern or a regular expression as a parameter. For example: Instead of passing:

bool nomeDaVariavel.Contains("#NUSAPRO");

pass something like:

String verifica = @"^#/[A-Z]{1,7}";
//Padrão que captura qualquer String 
//que comece com o "#", 
//seguido de um a sete caracteres de A a Z em caixa grande

bool nomeDaVariavel.Contains(verifica);

Of course the syntax is wrong, but it's just to get an idea of what I want.

If you can help, I'm grateful.

    
asked by anonymous 22.01.2016 / 23:35

1 answer

1

You need to use the Regex class to apply the regular expression to the strings you want to compare. The code below shows an example of how this can be done.

String verifica = @"^#[A-Z]{1,7}";
Regex verificaRegex = new Regex(verifica);
var negativos = new string[] { "ABCDEFG", "#aBCDEFG", "# ABCDEFg", "#aBCDEFG", "#1BCDEFG" };
var positivos = new string[] { "#ABCDEFG", "#ABCDEFG1", "#ABCDEFGHIJKL", "#ABCDEFG abc" };

Console.WriteLine("Negativos:");
foreach (var neg in negativos)
{
    Console.WriteLine(verificaRegex.IsMatch(neg));
}

Console.WriteLine("Positivos:");
foreach (var pos in positivos)
{
    Console.WriteLine(verificaRegex.IsMatch(pos));
}
    
23.01.2016 / 00:15