Doubts about using Contains with Regex in C#

Asked

Viewed 205 times

2

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

bool nomeDaVariavel.Contains("#NUSAPRO");

go through 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);

Sure the syntax is wrong, but it’s just to get an idea of what I intend.

If you could help, I’d be grateful.

  • Your intention is to rewrite the String.Contains() method for the entire application, or just have a call from a specific method to avoid using the Regex API directly?

1 answer

1

You need to use the class Regex to apply 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));
}
  • Carlos good evening. In case these "negatives" would be a protection to the data received? Because String itself is case sensitive, it would already block some character that is not capitalized and with space between or before it, etc certain?

  • Good evening. In case these "negatives" would be a protection to the data received or the input string to be analyzed? Because String itself is case sensitive, it would already block some character that is not capitalized and with space between or before it, etc certain?

  • The list of "positive" and "negative" cases are just a few strings I used to test the regular expression. What makes a string that starts with #a be considered negative (i.e., not match), is your regular expression. As you specified you only want the characters A-Z, then the expression will only do the match uppercase characters. If you also want to include lowercase, you can exchange the expression for $#[A-Za-z]{1,7}.

Browser other questions tagged

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