Home > Enterprise >  Mongodb Aggregator - Check if string contains digits or special chars
Mongodb Aggregator - Check if string contains digits or special chars

Time:06-22

I am using Mongo Aggregators to prepare queries.

I would like to check two things:

  • If my string has digits (e.g. "Luk3 Sk1w8lk3r");
  • If my string contains special characters (e.g. "L*ke Sk!w"lz")
  • Or if contains both (e.g. "L0ke Sk!w0l'z8")

I am trying to use the $regex method but It seems I have to specify too many fields:

{ value: { $regex: "!" } }

This only finds strings that contains "!", but I would like to find strings that may (or may not) contains more special chars.

CodePudding user response:

I found workaround using $match:

  1. if string contains digits:

{"value":{"$regex": "\d"}}

  1. if string contains special characters:

{"value":{"$regex": "[\.\*\ \?\^\${}\(\)|\]\[\\]"}}

Appreciated every future improvement on these queries!

CodePudding user response:

1. If my string has digits (e.g. "Luk3 Sk1w8lk3r");

Your filter {"value":{"$regex": "\d"}}.

2. If my string contains special characters (e.g. "L*ke Sk!w"lz")

{"value":{"$regex": "[.* ?^${}()|][\]"}}

The regex can be written little differently (without using the escape \ for all special characters):

"[.* ?^${}()|\]\[\\]"

You specify the escape \ for [, ] and \. Further, you can include other special characters like ! and ' within the regex.

3. Or if contains both (e.g. "L0ke Sk!w0l'z8")

  • "if contains both" - means the "AND" operation.
  • "contains digits or special chars" - means the "OR" operation (from this post's title)"

Here are regex for both:

  • To perform the "AND" operation, use this: "(?=.*[.'!* ?^${}()|\]\[\\])(?=.*[0-9])"
  • To perform the "OR" operation, use this: "[.'!* ?^${}()|\]\[\\]|\d"
  • Related