java comparing two Pattern objects

java, regex

Solution

Maybe I do not fully understand to the question. But as you can see in the following example, there is a default `java.lang.Object.equals(Object)` method for every Java Object. This method compares the references to the objects, i.e. uses the `==` operator.

package test;

import java.util.regex.Pattern;

public class Main {

  private static final Pattern P1 = Pattern.compile("//.*");
  private static final Pattern P2 = Pattern.compile("//.*");

  public static void main(String[] args) {
    System.out.println(P1.equals(P1));
    System.out.println(P1.equals(P2));
    System.out.println(P1.pattern().equals(P1.pattern()));
    System.out.println(P1.pattern().equals(P2.pattern()));
  }
}

Outputs:

true
false
true
true

Problem

Is there an easy way to compare two `Pattern` objects? I have a `Pattern` which compiled using the regex `"//"` to check for comments in a code. Since there are several regex to describe comments, I want to find a way to difference them. How can it be done? the `Pattern` class does not implements the `equals` method.

Original source