3

I'm trying to query MongoDB using spring but I can't get my regex to work.

I have a tree in mongodb as Materialized Paths as in MongoDB docs (http://www.mongodb.org/display/DOCS/Trees+in+MongoDB).

In the shell the query

db.categories.find({path:/^\w+,$/})

works fine to find the path before the first comma.

Ex.: {"path" : "a,"} gets returned but not {"path: "a,b,"} which is what I want.

How do I make the same query in spring? I've tried:

new Query(Criteria.where("path").regex("/^\\w+,$/"))

but this doesn't work.

Thank you

1
  • I don't know this Spring-MongoDB stuff. However, I know that you need to double-escape back-slashes in Java regexes. Also, you don't need the starting and ending slashes either: .regex("^\\\\w+,$") should work. Commented Oct 5, 2012 at 20:38

1 Answer 1

5

I just solved my problem.

query = new Query(Criteria.where("path").regex("^([A-Z]|[a-z])+,$"));

although \w stands for "any word character" which usually means alphanumeric, I just need the alphabet characters.

I can later throw [0-9] and \_ to have the same as \w.

If someone can explain how to make \w to work, I'll be very thankful :)

Sign up to request clarification or add additional context in comments.

2 Comments

in you first example you've used / int he begining an end, whereas in the second you didn't use / character.
Like 'tamas rev' said on the question comment, there is no need to use those slashes

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.