La_haine
La_haine

Reputation: 349

Mongodb Aggregator - Check if string contains digits or special chars

I am using Mongo Aggregators to prepare queries.

I would like to check two things:

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.

Upvotes: 0

Views: 256

Answers (2)

prasad_
prasad_

Reputation: 14317

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"

Upvotes: 2

La_haine
La_haine

Reputation: 349

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!

Upvotes: 1

Related Questions