1

I need to find all data matching with string who looking like this :

16041917
16041917-A
16041917-Z

So as you can see sometimes I can get -X suffix or sometimes no.

In my code I have the value of the number but I don't know if there is a suffix or not. So I try to make a regex to find if the number exist in my database.

{number : {$regex: "^16041917|^-[A-Z]$"}}

It works but I don't know if my regex will work for everything. Can you tell me if you have better ?

5
  • 2
    Try "^[0-9]{8}(?:-[A-Z])?$" Commented Sep 3, 2018 at 10:17
  • I don't want to get all number matching with this patern. I want specific number that is why I put the number inside my regex. This will be used like a variable in my code. I think my example is confusing I'll edit Commented Sep 3, 2018 at 10:19
  • try this 16041917(-[A-Z])?$ Commented Sep 3, 2018 at 10:20
  • It works yes but I think I need to append ^ at the beginning because it will match if I type 41917(-[A-Z])?$ and I want the exactly number Commented Sep 3, 2018 at 10:23
  • I suggested [0-9] because in your initial question you said you wanted to match 18689784 and 18689784-G. To only match specific number, just use it instead of [0-9]{8}. "^16041917(?:-[A-Z])?$" Commented Sep 3, 2018 at 10:25

1 Answer 1

1

To match any string starting with 16041917 and then having an optional sequence of - followed with a single uppercase ASCII letter use

"^16041917(?:-[A-Z])?$"

See the regex demo.

Details

  • ^ - start of string
  • 16041917 - a literal substring
  • (?:-[A-Z])? - an optional non-capturing group matching 1 or 0 occurrences of
    • - - a hyphen
    • [A-Z] - an uppercase ASCII letter
  • $ - end of string.
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.