0

if we are saying .matches() tries to match entire input string then why following returns false?

String input = "HOLIDAY"; String pattern = "H*I*Y";

input.matches(pattern) --> returns false;

Note: I have already looked at Regex doesn't work in String.matches()

Parth
  • 188
  • 1
  • 1
  • 9
  • 1
    `H*` means "letter `H`, repeated zero or more times", see Regex101.com (remember to choose appropriate regex flavor for your programming language). It's not wildcard like in globs. You probably want `H.*|.*Y`. – yeputons Nov 26 '21 at 05:12
  • 1
    `String pattern = "H\*I\*Y"` produces a compile error, so it won't "return" anything. What did you actually code? – Bohemian Nov 26 '21 at 11:40
  • @Bohemian I meant H * I * Y only but have put \ for stackoverflow editor escape! Else it was showing! Have edited now! H*I*Y – Parth Nov 27 '21 at 06:39
  • @yeputons thanks for explaining got it now!! But then why It works fine when we use pattern compile? – Parth Nov 27 '21 at 06:42

1 Answers1

2

Regex is not globbing!

Your regex "H*I*Y" does not mean "H then anything then I then anything then Y"; it means "any number of H (including none) followed by any number of I (including none) followed by a Y".

The regex equivalent of globbing's * is .*: the dot means "any character" an * means "any number of (including none)".

Try:

String pattern = "H.*I.*Y";
Bohemian
  • 412,405
  • 93
  • 575
  • 722