Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular Expression oddity, why does this happen?

Tags:

c#

regex

This simple regular expression matches the text of Movie. Am I wrong in reading this as "Q repeated zero or more times"? Why does it match, shouldn't it return false?

public class Program
{
    private static void Main(string[] args)
    {
        Regex regex = new Regex("Q*");
        string input = "Movie";
        if (regex.IsMatch(input))
        {
            Console.WriteLine("Yup.");
        }
        else
        {
            Console.WriteLine("Nope.");
        }
    }
}
like image 556
Jim Stahl Avatar asked Mar 20 '23 12:03

Jim Stahl


1 Answers

As you are saying correctly, it means “Q repeated zero or more times”. I this case, it’s zero times, so you are essentially trying to match "" in your input string. As IsMatch doesn’t care where it matches, it can match the empty string anywhere within your input string, so it returns true.

If you want to make sure that the whole input string has to match, you can add ^ and $: "^Q*$".

Regex regex = new Regex("^Q*$");
Console.WriteLine(regex.IsMatch("Movie")); // false
Console.WriteLine(regex.IsMatch("QQQ")); // true
Console.WriteLine(regex.IsMatch("")); // true
like image 115
poke Avatar answered Apr 06 '23 09:04

poke