2 * Svjatoslav Commons - shared library of common functionality. Author: Svjatoslav Agejenko.
3 * This project is released under Creative Commons Zero (CC0) license.
5 package eu.svjatoslav.commons.string;
7 public class GlobMatcher {
10 * Allow only for * in wildcards
12 private static boolean checkWildCardEnd(final String wildcardExpression,
13 int wildCardPosition) {
14 for (; wildCardPosition < wildcardExpression.length(); wildCardPosition++) {
15 final char wildCardChar = wildcardExpression
16 .charAt(wildCardPosition);
17 if (wildCardChar != '*')
26 * Test input string against wildcard expression.
27 * * -- corresponds to any amount of characters.
28 * ? -- corresponds to any single character.
31 * @param inputString input string
32 * @param wildcardExpression wildcard expression
33 * @return <code>true</code> if input string matches input pattern
35 public static boolean match(final String inputString,
36 final String wildcardExpression) {
38 if (inputString == null)
41 if (wildcardExpression == null)
46 for (i = 0; i < inputString.length(); i++) {
47 if (i >= wildcardExpression.length())
49 final char wildCardChar = wildcardExpression.charAt(i);
50 if (wildCardChar == '*')
51 return matchPiece(inputString, i, wildcardExpression, i + 1);
52 if (wildCardChar != '?')
53 if (inputString.charAt(i) != wildCardChar)
57 return checkWildCardEnd(wildcardExpression, i);
60 private static boolean matchPiece(final String inputString,
61 final int inputStringIndex, final String wildcardExpression,
62 final int wildCardExpressionIndex) {
64 int wildCardPosition = wildCardExpressionIndex;
66 for (int i = inputStringIndex; i < inputString.length(); i++) {
68 wildCardPosition = wildCardExpressionIndex;
73 for (int j = i; j < inputString.length(); j++) {
74 if (wildCardPosition >= wildcardExpression.length())
75 break subMatchAttempt;
76 final char wildCardChar = wildcardExpression
77 .charAt(wildCardPosition);
79 if (wildCardChar == '*')
80 return matchPiece(inputString, j, wildcardExpression,
81 wildCardPosition + 1);
83 if (wildCardChar != '?')
84 if (inputString.charAt(j) != wildCardChar)
85 break subMatchAttempt;
90 return checkWildCardEnd(wildcardExpression, wildCardPosition);
95 return checkWildCardEnd(wildcardExpression, wildCardPosition);