-5

With this call,

System.out.println(Pattern.matches("[c&&c]", "c"));

I got true. However, with this call,

System.out.println(Pattern.matches("c&&c", "c"));

I got false. The second call does not get any exceptions thrown, which means it's a valid regular expression. However, I'm not sure that's acceptable because, in Java API, the operator && seems to only occur between brackets. Then, what's the meaning of && in the second call?

b1sub
  • 2,266
  • 1
  • 10
  • 29
  • Did you look at the [Pattern documentation](http://docs.oracle.com/javase/8/docs/api/java/util/regex/Pattern.html) for an answer? – VGR May 10 '17 at 18:46

2 Answers2

1

What's the meaning of && in the second call ?

[c&&c] is character class with means either of the characters in it.

I got true.

Because c matches either of c&&c. Basically [c&] will be enough.

c&&c means literally. c followed by & followed by & followed by c. Which does not match just c.

Rahul
  • 2,288
  • 5
  • 25
  • Just to elaborate on the first point: `[c&&c]` is a character class consisting of `c`, `&`, `&`, or `c` -- which is of course equivalent to a class consisting of `c` or `&`, which is what Rahul was referring to. – yshavit May 10 '17 at 18:26
1
  • [] allow you to match any characters between them. So [c&&c] allows c or & to appear in the string that you are trying to match. So you get a successful match for just c or for just &
  • c&&c is a literal which will only match with c&&c appearing within a text. So it doesn't match with your test string c.
degant
  • 4,466
  • 1
  • 13
  • 28