Match only alpha numeric characters
mongodb, regex
Solution
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
Problem
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.