-1
String p = "(a|ab|c)*";

String s = "aabcab";

Boolean b = s.matches(p);

System.out.println(b);

This pattern 'p' matches:

1) 0 or more single 'a': a, aa, aaa
2) 0 or more single 'ab': ab, abab, ababab
3) 0 or more single 'c': c, cc, ccc

Why does it match 'aabcab'? In the 3 patterns above, there isn't any string consisting of a mixture of characters 'a', 'b', and 'c'

ling
  • 1,305
  • 1
  • 13
  • 21
  • 2
    The star matches any number of the preceding group, in this case 'a' - 'ab' - 'c' - 'ab'. – Elliott Frisch Dec 07 '19 at 06:07
  • @ElliottFrisch, the order of the group doesn't matter? i.e. 'ccab' – ling Dec 07 '19 at 06:21
  • It does not when the pattern is a or ab or c any number of times. You did not specify a pattern with an order. Also, you could have *tried* `System.out.println("ccab".matches("(a|ab|c)*"));` (but since you ask, it's `true`). – Elliott Frisch Dec 07 '19 at 06:24
  • What is the actual logic behind what you are trying to match? – Tim Biegeleisen Dec 07 '19 at 06:25
  • @TimBiegeleisen, I am reading and just trying to understand how it matches, given the string and pattern. – ling Dec 07 '19 at 06:38

1 Answers1

3

The Kleene star operation doesn't distribute over the alternative: the rule you were most likely looking for is: (a*)|(ab)*|(c*).

Your pattern p will match any sequence of characters formed be zero or more repetitions of ANY of the three given alternatives over and over again, instead of repetitions of each type that may not mix.

CinchBlue
  • 4,697
  • 19
  • 46