skip to Main Content

If I want to find "KFC", "EU 8RF", and IK-OTP simultaneously, what should the code look like?

My code is :

db.business.find({name:/^[A-Zs?d?-?]*$/}, {name:1}).sort({"name":1})

but it will return the name that is whole number, such as 1973, 1999. How should I improve my code? TIA

2

Answers


  1. Use a lookahead to require at least one letter.

    ^(?=.*[A-Z])[A-Zds-]+$
    

    DEMO

    Login or Signup to reply.
  2. You can use

    ^(?=[d -]*[A-Z])[A-Zd]+(?:[ -][A-Zd]+)*$
    

    See the regex demo.

    Details:

    • ^ – start of string
    • (?=[d -]*[A-Z]) – a positive lookahead that requires an uppercase ASCII letter after any zero or more digits, spaces or hyphens immediately to the right of the current location
    • [A-Zd]+ – one or more uppercase ASCII letters or digits
    • (?:[ -][A-Zd]+)* – zero or more repetitions of a space or - and then one or more uppercase ASCII letters or digits
    • $ – end of string.
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search