Skip to content

Instantly share code, notes, and snippets.

@pOH7
Created August 22, 2018 02:31
Show Gist options
  • Save pOH7/c2587bf0d93396cb05db7d8943208a14 to your computer and use it in GitHub Desktop.
Save pOH7/c2587bf0d93396cb05db7d8943208a14 to your computer and use it in GitHub Desktop.
Searching string with special characters in MongoDB document
/**
* Searching string with special characters in MongoDB document
* @param keyword string with special characters
* @return pattern, e.g. Criteria.where(field).regex(pattern);
*/
public static Pattern generatePattern(String keyword) {
checkArgument(StringUtils.isNotEmpty(keyword));
keyword = keyword.replace("*", "\\*")
.replace(".", "\\.");
return Pattern.compile("^.*" + keyword + ".*$", Pattern.CASE_INSENSITIVE);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment