Home java java: string.matches () or Matcher and Pattern?

java: string.matches () or Matcher and Pattern?




What is the fundamental difference between the String.matches (Regex) method from using a bunch of classes PATTERN and MATCHER ?

In which cases, it is better to use the first, and in what is the second?

Answer 1, Authority 100%

Matcher / Pattern has a greater productivity. Operates compiled regular expression, while string.matches produces recompiling constantly. Therefore, if you use the search on the same regular regularly more than once Matcher / Pattern will give performance gain.

The inner implementation is no different, String class appeals to Matcher / Pattern

Public Boolean Matches (String Regex) {
  Return Pattern.Matches (Regex, this);
Public Static Boolean Matches (String Regex, Charsequence Input) {
  Pattern P = Pattern.compile (Regex);
  Matcher M = P.Matcher (INPUT);
  Return M.Matches ();

Answer 2, Authority 40%

string.matches – it’s just a quick equivalent of the pattern.compile chain (...). Matcher (...). Matches () . Using Pattern / Matcher directly allows you to:

  • Set flags when compiling regular expression (for example, pattern.literal ).
  • re-use one regular expression many times.
  • Search is not a complete coincidence, but a partial (Matcher.find () )
  • find captured characters group (matcher.group () )
  • Conduct an effective search with replacement using Matcher.appendreplacement / Appendtail

and so on. string.matches () gives a quick way to use the most popular function, but in general these functions are a lot.

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions