0

Why test() prints 'matches' in the first statement? I thinks this regex should always print 'not matches' if \\W sign is omitted cause the first [a-z]+ takes everything till the end of string (cause \\W is omitted) and there is not characters to fit the second [a-z]+

class Test
{
    public static void main(String[] args)
    {
        test("mymail");
        test("my.mail");
        
    }
    
    public static void test(String stringToTest)
    {
        String regex = "[a-z]+\\W?[a-z]+";
        if (stringToTest.matches(regex))
        {
            System.out.println("matches");
        }
        else
        {
            System.out.println("not matches");
        }
    }
}
Denis_newbie
  • 1,002
  • 2
  • 12
  • 1
    `?` means zero to one match. Emphasis on **zero**. So it just decided to not consider the `\\W` and continue with `[a-z]+[a-z]+` basically, which matches. – Zabuzard Jun 22 '20 at 15:54
  • 2
    (simplified) The first `[a-z]+` grabs until the end -> it releases a characters -> `\\W?` then is matched but since it's optional is skipped -> the single character released is matched by the final `[a-z]+` – VLAZ Jun 22 '20 at 15:54
  • 2
    See https://regex101.com/r/xdFsrV/1, use capturing groups to see what is going on in such cases. – Wiktor Stribiżew Jun 22 '20 at 15:55
  • 2
    `mymail` matches `[a-z]+\\W?[a-z]+` with `mymai` as the first `[a-z]+`, nothing as the `\\W?`, and `l` as the second `[a-z]+`. – khelwood Jun 22 '20 at 15:55

0 Answers0