Regular expression randomness, why is this happening?

This simple regular expression matches the text Movie. Am I mistaken reading this as "Q repeats zero or more times"? Why does it match, should it not 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.");
        }
    }
}
+4
source share
2 answers

As you say correctly, this means "Q repeats zero or more times." In this case, its times are zero, so you are essentially trying to match ""in your input line. Since it IsMatchdoes not care about where it matches, it can match an empty string anywhere in your input string, so it returns true.

, , ^ $: "^Q*$".

Regex regex = new Regex("^Q*$");
Console.WriteLine(regex.IsMatch("Movie")); // false
Console.WriteLine(regex.IsMatch("QQQ")); // true
Console.WriteLine(regex.IsMatch("")); // true
+5

Q, 0 . , 0. , .

- (0 ), - , , , . :

(Q*)

.Matches Groups[1].Value, , . , .

, , , .Contains. , , , .

+2

Source: https://habr.com/ru/post/1527962/


All Articles