Regex to match only uppercase strings with or without numbers in specific format

Viewed 325

I have the following list of strings:

list1 = ['KVC Company','this is a sample', 'TEL 555-555-5555', 'DATE: 05/12/2021', 
'50 KG LOADER', 'COMPUTER SCIENCE', '13445556 AAA', 'MONDAY', 'AMT: 60', 'plenty', 
'data sources','USA 00000','EXM: J. Smith', 'X', 'FH']

I'm using the following regex to filter the list:

r'\b[A-Z]{3,}(?:\s+[A-Z]{3,})*\b.*$'

This regex matches all the strings that begin with uppercase letters but doesn't consider the rest of the letters.

I'm getting the output as follows,

output = ['KVC Company', 'TEL 555-555-5555', 'DATE: 05/12/2021', 'LOADER', 
'COMPUTER SCIENCE', 'AAA','MONDAY', 'AMT: 60', 'USA 00000','EXM: J. Smith']

My desired output is as shown below,

['50 KG LOADER', 'COMPUTER SCIENCE', 'MONDAY' ]

which contains only strings that are completely uppercase and doesn't have any symbols and have only numbers not more than 2 digits.

How can I filter out all other strings and return only string which are completely uppercase having only 2 digit numbers and doesn't have any symbols like :,/,- and lower case letters anywhere in the string.

1 Answers

You may use this regex in Python:

^(?!.*\d{3})(?=.*[A-Z]{3})[A-Z\d ]+$

RegEx Demo

RegEx Details:

  • ^: Start
  • (?!.*\d{3}): Negative lookahead to assert that we don't have 3 digits anywhere
  • (?=.*[A-Z]{3}): Positive lookahead to assert that we have at least 3 consecutive uppercase letters, somewhere
  • [A-Z\d ]+: Match 1+ of uppercase letter or digit or space
  • $: End
Related