2 * Svjatoslav Commons - shared library of common functionality.
3 * Copyright ©2012-2013, Svjatoslav Agejenko, svjatoslav@svjatoslav.eu
5 * This program is free software; you can redistribute it and/or
6 * modify it under the terms of version 2 of the GNU General Public License
7 * as published by the Free Software Foundation.
10 package eu.svjatoslav.commons.string;
12 public class WildCardMatcher {
15 * Allow only for * in wildcards
17 private static boolean checkWildCardEnd(final String wildcardExpression,
18 int wildCardPosition) {
19 for (; wildCardPosition < wildcardExpression.length(); wildCardPosition++) {
20 final char wildCardChar = wildcardExpression
21 .charAt(wildCardPosition);
22 if (wildCardChar != '*')
31 * Test input string against wildcard expression.
32 * * -- corresponds to any amount of characters.
33 * ? -- corresponds to any single character.
37 public static boolean match(final String inputString,
38 final String wildcardExpression) {
42 for (i = 0; i < inputString.length(); i++) {
43 if (i >= wildcardExpression.length())
45 final char wildCardChar = wildcardExpression.charAt(i);
46 if (wildCardChar == '*')
47 return matchPiece(inputString, i, wildcardExpression, i + 1);
48 if (wildCardChar != '?')
49 if (inputString.charAt(i) != wildCardChar)
53 return checkWildCardEnd(wildcardExpression, i);
56 private static boolean matchPiece(final String inputString,
57 final int inputStringIndex, final String wildcardExpression,
58 final int wildCardExpressionIndex) {
60 int wildCardPosition = wildCardExpressionIndex;
62 for (int i = inputStringIndex; i < inputString.length(); i++) {
64 wildCardPosition = wildCardExpressionIndex;
68 for (int j = i; j < inputString.length(); j++) {
69 if (wildCardPosition >= wildcardExpression.length())
70 break subMatchAttempt;
71 final char wildCardChar = wildcardExpression
72 .charAt(wildCardPosition);
74 if (wildCardChar == '*')
75 return matchPiece(inputString, j, wildcardExpression,
76 wildCardPosition + 1);
78 if (wildCardChar != '?')
79 if (inputString.charAt(j) != wildCardChar)
80 break subMatchAttempt;
85 return checkWildCardEnd(wildcardExpression, wildCardPosition);
90 return checkWildCardEnd(wildcardExpression, wildCardPosition);