define a regular expression in python
Question: I am trying to use regular expressions in python to say a 4 characters string
with 1st character being a digit and 3 other characters being either a digit
or a capital letter. Here's examples of patterns that should match 1CTT, 2IR8,
35TR, 4T1R

I tried many ways, here's the last code I tried :

    
    
    exp=re.compile("[0-9]{1}([A-Z0-9]{3})")
    

Thank you for your help !


Answer: The expression you've tried last, looks correct and should match the provided
test strings. Though you don't have to specify `{1}` and there is no need for
a capturing group (the parenthesis):

    
    
    >>> import re
    >>> text = "text, 1CTT, 2IR8, 35TR, 4T1R, smth else"
    >>> pattern = re.compile(r"[0-9][A-Z0-9]{3}")
    >>> pattern.findall(text)
    ['1CTT', '2IR8', '35TR', '4T1R']
    

You might need to additionally add the _word boundary_ constraint (thanks to
@Jon Clements):

    
    
    >>> text = "text, 1CTT, 2IR8, 35TR, 4T1R, smth else, 35TT35XYZ"
    >>> pattern = re.compile(r"\b[0-9][A-Z0-9]{3}\b")
    >>> pattern.findall(text)
    ['1CTT', '2IR8', '35TR', '4T1R']
    

