View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one or more
3    * contributor license agreements.  See the NOTICE file distributed with
4    * this work for additional information regarding copyright ownership.
5    * The ASF licenses this file to You under the Apache License, Version 2.0
6    * (the "License"); you may not use this file except in compliance with
7    * the License.  You may obtain a copy of the License at
8    *
9    *      https://www.apache.org/licenses/LICENSE-2.0
10   *
11   * Unless required by applicable law or agreed to in writing, software
12   * distributed under the License is distributed on an "AS IS" BASIS,
13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   * See the License for the specific language governing permissions and
15   * limitations under the License.
16   */
17  package org.apache.commons.text.similarity;
18  
19  import java.util.Locale;
20  
21  /**
22   * A matching algorithm that is similar to the searching algorithms implemented in editors such
23   * as Sublime Text, TextMate, Atom and others.
24   *
25   * <p>
26   * One point is given for every matched character. Subsequent matches yield two bonus points. A higher score
27   * indicates a higher similarity.
28   * </p>
29   *
30   * <p>
31   * This code has been adapted from Apache Commons Lang 3.3.
32   * </p>
33   *
34   * @since 1.0
35   */
36  public class FuzzyScore {
37  
38      /**
39       * Locale used to change the case of text.
40       */
41      private final Locale locale;
42  
43      /**
44       * Constructs a new instance for a {@link Locale}-specific {@link FuzzyScore}.
45       *
46       * @param locale The string matching logic is case insensitive. A {@link Locale} is necessary to normalize both Strings to lower case.
47       * @throws IllegalArgumentException This is thrown if the {@link Locale} parameter is {@code null}.
48       */
49      public FuzzyScore(final Locale locale) {
50          if (locale == null) {
51              throw new IllegalArgumentException("Locale must not be null");
52          }
53          this.locale = locale;
54      }
55  
56      /**
57       * Computes the Fuzzy Score which indicates the similarity score between two Strings.
58       *
59       * <pre>
60       * score.fuzzyScore(null, null)                          = Throws {@link IllegalArgumentException}
61       * score.fuzzyScore("not null", null)                    = Throws {@link IllegalArgumentException}
62       * score.fuzzyScore(null, "not null")                    = Throws {@link IllegalArgumentException}
63       * score.fuzzyScore("", "")                              = 0
64       * score.fuzzyScore("Workshop", "b")                     = 0
65       * score.fuzzyScore("Room", "o")                         = 1
66       * score.fuzzyScore("Workshop", "w")                     = 1
67       * score.fuzzyScore("Workshop", "ws")                    = 2
68       * score.fuzzyScore("Workshop", "wo")                    = 4
69       * score.fuzzyScore("Apache Software Foundation", "asf") = 3
70       * </pre>
71       *
72       * @param term  a full term that should be matched against, must not be null.
73       * @param query the query that will be matched against a term, must not be null.
74       * @return result score.
75       * @throws IllegalArgumentException if the term or query is {@code null}.
76       */
77      public Integer fuzzyScore(final CharSequence term, final CharSequence query) {
78          if (term == null || query == null) {
79              throw new IllegalArgumentException("CharSequences must not be null");
80          }
81          // fuzzy logic is case insensitive. We normalize the Strings to lower
82          // case right from the start. Turning characters to lower case
83          // via Character.toLowerCase(char) is unfortunately insufficient
84          // as it does not accept a locale.
85          final String termLowerCase = term.toString().toLowerCase(locale);
86          final String queryLowerCase = query.toString().toLowerCase(locale);
87          // the resulting score
88          int score = 0;
89          // the position in the term which will be scanned next for potential
90          // query character matches
91          int termIndex = 0;
92          // index of the previously matched character in the term
93          int previousMatchingCharacterIndex = Integer.MIN_VALUE;
94          for (int queryIndex = 0; queryIndex < queryLowerCase.length(); queryIndex++) {
95              final char queryChar = queryLowerCase.charAt(queryIndex);
96              boolean termCharacterMatchFound = false;
97              for (; termIndex < termLowerCase.length() && !termCharacterMatchFound; termIndex++) {
98                  final char termChar = termLowerCase.charAt(termIndex);
99                  if (queryChar == termChar) {
100                     // simple character matches result in one point
101                     score++;
102                     // subsequent character matches further improve
103                     // the score.
104                     if (previousMatchingCharacterIndex + 1 == termIndex) {
105                         score += 2;
106                     }
107                     previousMatchingCharacterIndex = termIndex;
108                     // we can leave the nested loop. Every character in the
109                     // query can match at most one character in the term.
110                     termCharacterMatchFound = true;
111                 }
112             }
113         }
114         return score;
115     }
116 
117     /**
118      * Gets the locale.
119      *
120      * @return The locale
121      */
122     public Locale getLocale() {
123         return locale;
124     }
125 
126 }