What is the difference between the pattern()
method and the toString()
method in the Pattern
class?
The doc says:
public String pattern()
Returns the regular expression from which this pattern was compiled.
public String toString()
Returns the string representation of this pattern. This is the regular expression from which this pattern was compiled.
Even their implementation returns the same result:
import java.util.regex.*;
class Test {
public static void main(String[] args) {
Pattern p = Pattern.compile("[a-zA-Z]+\\.?");
String s = p.pattern();
String d = p.toString();
System.out.println(s);
System.out.println(d);
}
}
I see no difference, so why are there two methods? Or am I missing something?
Because each class has a toString()
method which was inherited from Object
. The toString()
method is supposed to return a string which represents the object the best way it can, if it is even possible to create some kind of string representation.
The name toString()
is pretty vague, so they added a method pattern()
which is more straightforward.
And because they wanted toString()
to return something clever they used the pattern of the regex, which is a good string representation for the Pattern
class.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With