简体   繁体   中英

regex get closest match to given string

I have a regex search in my code for getting names in my db by the given string. The problem I'm having is that if I have a name "Jim" and a name "Jimmy", I always get the "Jimmy" for some reason.

let regexp = new RegExp(userName, "i");
let name = await names.findOne({ name: regexp });

So when I type in "Jimmy" I get Jimmy, "Jimm" I get Jimmy, all good, but when I try to find "Jim" I get Jimmy, so there's no way for me to get Jim.

Also I can't find names if they have ( or ) ? Ex: Tom (Thomas), and i search exactly "Tom (Thomas)" it doesn't find it at all, but that might be a Mongoose problem.

I think this is a problem with how you're ordering your database, or at least the results that you query from it. You can either sort the table, or sort your results after you query them.

Try using one of these (alphabetical or reverse alphabetical):

let name = await names.sort({ name: 1 }).findOne({ name: regexp });
let name = await names.sort({ name: -1 }).findOne({ name: regexp });

For your second question, it looks like what you want to investigate "Fuzzy Matching" - so that things like Tom can return results like Thomas .

Try taking a look at this:

Fuzzy Searching with Mongodb?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM