Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Match only alpha numeric characters

Tags:

regex

mongodb

This question is actually an extension to following.

Ignore special characters before match conditions

I am using mongodb aggregate to find some product from a table. Following is the part of query I need to improve

{
   $match : { "name" :  { $regex :  "kdf8210"} }
}

Now that do match any product which contains word "kdf8210" anywhere in it's name.. But I need it to match it with the following as well.

kdf.8210, kdf-8210, kdf.82-10

Basically match should ignore any special characters in between.

I just learned that $where cannot be used as part of aggregate pipeline, so the answers from referenced questions are not of much help.

like image 595
Ankit Avatar asked May 19 '26 12:05

Ankit


1 Answers

You can use something like this:

^k[.-]?d[.-]?f[.-]?8[.-]?2[.-]?1[.-]?0$ 
  • This allows special chars . and - to be inserted anywhere (except the beginning or the tail end).
  • If you want to allow more special chars, we can tweak the [.-]

Remove the ^ and $ anchors if you are not trying to match the whole string.

  • The ^ anchor asserts that we are at the beginning of the string
  • The $ anchor asserts that we are at the end of the string

See demo

like image 130
zx81 Avatar answered May 21 '26 05:05

zx81