Regular Expression Wildcard Matching

Unless you want some funny behaviour, I would recommend you use \w instead of .

. matches whitespace and other non-word symbols, which you might not want it to do.

So I would replace ? with \w and replace * with \w*

Also if you want * to match at least one character, replace it with \w+ instead. This would mean that ben* would match bend and bending but not ben - it's up to you, just depends what your requirements are.


Take a look at this library: https://github.com/alenon/JWildcard

It wraps all not wildcard specific parts by regex quotes, so no special chars processing needed: This wildcard:

"mywil?card*"

will be converted to this regex string:

"\Qmywil\E.\Qcard\E.*"

If you wish to convert wildcard to regex string use:

JWildcard.wildcardToRegex("mywil?card*");

If you wish to check the matching directly you can use this:

JWildcard.matches("mywild*", "mywildcard");

Default wildcard rules are "?" -> ".", "" -> ".", but you can change the default behaviour if you wish, by simply defining the new rules.

JWildcard.wildcardToRegex(wildcard, rules, strict);

You can use sources or download it directly using maven or gradle from Bintray JCenter: https://bintray.com/yevdo/jwildcard/jwildcard

Gradle way:

compile 'com.yevdo:jwildcard:1.4'

Maven way:

<dependency>
  <groupId>com.yevdo</groupId>
  <artifactId>jwildcard</artifactId>
  <version>1.4</version>
</dependency>

Tags:

Java

Regex