Search code examples
regexmongodbspring-data

Spring data - MongoDB - $regex search


I use Spring data with MongoDB in my application, one of my repository classes look like this:

public interface ProductRepository extends MongoRepository<Product, String> {

@Query("{$or : [{'name': { $regex: ?0, $options:'i' }}, {'description': { $regex: ?0, $options:'i' }}]}")
List<Product> findProductByRegexString(final String regexString);

...
}

This method I invoke like this:

public class ProductServiceTest extends AbstractServiceTest {

@Test
public void shouldSearchProductBySubString() throws BusinessException {

    final Tenant tenant = new Tenant();
    tenant.setName("TestTenant");
    final Tenant createdTenant = tenantService.create(tenant);
    Assert.assertNotNull(createdTenant);

    final Product product1 = new Product();
    product1.setName("Wander");
    product1.setDescription("Das ist das Test Produkt 1");
    product1.setTenant(createdTenant);
    final Product createdProduct1 = productService.create(product1);
    Assert.assertNotNull(createdProduct1);

    final Product product2 = new Product();
    product2.setName("Wunder baum");
    product2.setDescription("Ein different Produkt 2");
    product2.setTenant(createdTenant);
    final Product createdProduct2 = productService.create(product2);
    Assert.assertNotNull(createdProduct2);

    final List<Product> allProducts = productService.findAllProductsByTenant(createdTenant);
    Assert.assertEquals(2, allProducts.size());

    final List<Product> products = productService.findProductsByRegex("/^Wand/");
    Assert.assertEquals(1, products.size());
    }
}

and it works fine. If I try to use this chars:

regex

e.g:

final List<Product> products = productService.findProductsByRegex("/^Wand/");

I do not get any result with string /^Wand/ Does anyone have any explanation why it does not work with /^Wand/.


Solution

  • You might also need to quote:

    public static String escapeForRegex(String input) {
        return input.replace("\\", "\\\\")
                    .replace(".", "\\.")
                    .replace("*", "\\*")
                    .replace("+", "\\+")
                    .replace("?", "\\?")
                    .replace("{", "\\{")
                    .replace("}", "\\}")
                    .replace("(", "\\(")
                    .replace(")", "\\)")
                    .replace("[", "\\[")
                    .replace("]", "\\]")
                    .replace("^", "\\^")
                    .replace("$", "\\$")
                    .replace("|", "\\|");
    }