|
1
|
|
|
/* |
|
2
|
|
|
* |
|
3
|
|
|
* Copyright 2014, Armenak Grigoryan, and individual contributors as indicated |
|
4
|
|
|
* by the @authors tag. See the copyright.txt in the distribution for a |
|
5
|
|
|
* full listing of individual contributors. |
|
6
|
|
|
* |
|
7
|
|
|
* This is free software; you can redistribute it and/or modify it |
|
8
|
|
|
* under the terms of the GNU Lesser General Public License as |
|
9
|
|
|
* published by the Free Software Foundation; either version 2.1 of |
|
10
|
|
|
* the License, or (at your option) any later version. |
|
11
|
|
|
* |
|
12
|
|
|
* This software is distributed in the hope that it will be useful, |
|
13
|
|
|
* but WITHOUT ANY WARRANTY; without even the implied warranty of |
|
14
|
|
|
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU |
|
15
|
|
|
* Lesser General Public License for more details. |
|
16
|
|
|
* |
|
17
|
|
|
*/ |
|
18
|
|
|
|
|
19
|
|
|
|
|
20
|
|
|
|
|
21
|
|
|
package com.strider.datadefender.utils; |
|
22
|
|
|
|
|
23
|
|
|
import java.util.Locale; |
|
24
|
|
|
import java.util.regex.Pattern; |
|
25
|
|
|
|
|
26
|
|
|
/** |
|
27
|
|
|
* Simple matcher to mimic SQL LIKE queries. |
|
28
|
|
|
* |
|
29
|
|
|
* At the moment only "%", "_" and "?" are supported. |
|
30
|
|
|
* |
|
31
|
|
|
* @author Zaahid Bateson |
|
32
|
|
|
*/ |
|
33
|
|
|
public class LikeMatcher { |
|
34
|
|
|
final private String regex; |
|
35
|
|
|
|
|
36
|
|
|
/** |
|
37
|
|
|
* Initializes a LikeMatcher with the given pattern. |
|
38
|
|
|
* |
|
39
|
|
|
* @param pattern the LIKE query pattern |
|
40
|
|
|
*/ |
|
41
|
5 |
|
public LikeMatcher(final String pattern) { |
|
42
|
|
|
|
|
43
|
|
|
// splitting on '?', '_', and '%' with look-behind and look-ahead so they're included in the split array |
|
44
|
5 |
|
final String[] parts = pattern.split("((?<=[\\?\\_\\%])|(?=[\\?\\_\\%]))"); |
|
45
|
5 |
|
final StringBuilder reg = new StringBuilder("^"); |
|
46
|
|
|
|
|
47
|
5 |
|
for (final String part : parts) { |
|
48
|
46 |
|
if ("%".equals(part)) { |
|
49
|
6 |
|
reg.append(".*?"); |
|
50
|
34 |
|
} else if ("?".equals(part) || "_".equals(part)) { |
|
51
|
6 |
|
reg.append('.'); |
|
52
|
|
|
} else { |
|
53
|
11 |
|
reg.append(Pattern.quote(part.toLowerCase(Locale.ENGLISH))); |
|
54
|
|
|
} |
|
55
|
|
|
} |
|
56
|
|
|
|
|
57
|
5 |
|
reg.append('$'); |
|
58
|
5 |
|
this.regex = reg.toString(); |
|
59
|
|
|
} |
|
60
|
|
|
|
|
61
|
|
|
/** |
|
62
|
|
|
* Returns true if the given string matches the Like pattern. |
|
63
|
|
|
* |
|
64
|
|
|
* @param str the string to test against |
|
65
|
|
|
* @return |
|
66
|
|
|
*/ |
|
67
|
25 |
|
public boolean matches(final String str) { |
|
68
|
25 |
|
return str.toLowerCase(Locale.ENGLISH).matches(regex); |
|
69
|
|
|
} |
|
70
|
|
|
} |
|
71
|
|
|
|
|
72
|
|
|
|
|
73
|
|
|
//~ Formatted by Jindent --- http://www.jindent.com |
|
74
|
|
|
|