Last active
May 27, 2021 08:24
-
-
Save hydra1983/7509217 to your computer and use it in GitHub Desktop.
Convert wildcard pattern to regular expression to match strings
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Main { | |
public static void main(String[] args) { | |
test("<html*", "<html></html>"); | |
test("12*?", "12345"); | |
test("12*4?", "12345"); | |
} | |
private static void test(String pattern, String input) { | |
Pattern p = Pattern.compile(pattern); | |
System.out.println(pattern + " : " + input + " matches? " | |
+ p.match(input)); | |
} | |
} | |
public final class Pattern { | |
private static final char ESCAPES[] = { '$', '^', '[', ']', '(', ')', '{', | |
'|', '+', '\\', '.', '<', '>' }; | |
public static Pattern compile(String pattern) { | |
return new Pattern(pattern); | |
} | |
private Pattern(String pattern) { | |
regexp = wildcardToRegexp(pattern); | |
} | |
private String regexp; | |
public boolean match(String input) { | |
if (input == null) { | |
return false; | |
} | |
return input.matches(this.regexp); | |
} | |
private String wildcardToRegexp(String pattern) { | |
String result = "^"; | |
for (int i = 0; i < pattern.length(); i++) { | |
char ch = pattern.charAt(i); | |
boolean isEscaped = false; | |
for (int j = 0; j < ESCAPES.length; j++) { | |
if (ch == ESCAPES[j]) { | |
result += "\\" + ch; | |
isEscaped = true; | |
break; | |
} | |
} | |
if (!isEscaped) { | |
if (ch == '*') { | |
result += ".*"; | |
} else if (ch == '?') { | |
result += "."; | |
} else { | |
result += ch; | |
} | |
} | |
} | |
result += "$"; | |
return result; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment