Java: Test if String matches wildcard expression


The following Java method tests if a string matches a wildcard expression (supporting ? for exactly one character or * for an arbitrary number of characters):

/**
 * @param text Text to test
 * @param pattern (Wildcard) pattern to test
 * @return True if the text matches the wildcard pattern
 */
public static boolean match(String text, String pattern)
{
  return text.matches(pattern.replace("?", ".?").replace("*", ".*?"));
}

Here are some tests for this method:

Assert.assertFalse(match("HELLO WORLD", "ELLO"));
Assert.assertFalse(match("HELLO WORLD", "HELLO"));
Assert.assertFalse(match("HELLO WORLD", "*HELLO"));
Assert.assertFalse(match("HELLO WORLD", "HELLO WORLD2"));
Assert.assertFalse(match("HELLO WORLD", "HELLO WORL"));
Assert.assertFalse(match("HELLO WORLD", "hello world"));

Assert.assertTrue(match("HELLO WORLD", "*ELLO*"));
Assert.assertTrue(match("HELLO WORLD", "HELLO*"));
Assert.assertTrue(match("HELLO WORLD", "*LLO*"));
Assert.assertTrue(match("HELLO WORLD", "HELLO WORLD"));
,

One response to “Java: Test if String matches wildcard expression”

Leave a Reply

Your email address will not be published. Required fields are marked *