-5

Why does this regex evaluation returns 'false' ? Pattern.matches("[abc]?", "abc") // false.

As per definition '?' evaluates if the string matches 'zero or 'one' occurrence of a or b or c. To my understanding, there is exactly 'one' occurrence of each of a , b, c so it should be true, but it is false. Why?

In case of next line of code- Pattern.matches("[abc]+", "abc") / returns true ( evaluates one or more occurrence of a or b or c ) which is correct, as there is one occurrence of each of a, b, c.

As long as there is only one occurrence, '?' or '+' both should evaluate same. I am not able to understand how 'false' is evaluated in case of '?' Can some one please explain it?

import java.util.regex.*;
public class Main
    {
        public static void main(String[] args) {
            System.out.println(Pattern.matches("[abc]?", "abc")); //false (a or b or c comes zero or one time);
            System.out.println(Pattern.matches("[abc]+", "abc")); //true  (a or b or c comes one or more time)
    }
}
imraklr
  • 218
  • 3
  • 11
Ajay Singh
  • 441
  • 6
  • 18

1 Answers1

0

The regular expression [abc]? matches zero or one character that can be either a, b, or c. Thus it does not match abc. Positive matches would be the empty string, a, b, or c.

On the other hand [abc]+ matches one or more characters that can be either a, b, or c. Therefore, it can match the 3 character string abc. Also aaa or bbba would match.

Henry
  • 42,982
  • 7
  • 68
  • 84