Home > Software engineering >  Regex How can I find names only written in upper-case letters(mandatory), and the names may also con
Regex How can I find names only written in upper-case letters(mandatory), and the names may also con

Time:05-18

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-Z\s?\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

CodePudding user response:

Use a lookahead to require at least one letter.

^(?=.*[A-Z])[A-Z\d\s-] $

DEMO

CodePudding user response:

You can use

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

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-Z\d] - one or more uppercase ASCII letters or digits
  • (?:[ -][A-Z\d] )* - zero or more repetitions of a space or - and then one or more uppercase ASCII letters or digits
  • $ - end of string.
  • Related