Regex for fixed width field

后端 未结 2 591
误落风尘
误落风尘 2021-01-13 17:31

I need to match a fixed width field on a file layout with a regular expression. The field is numeric/integer, always have four characters and is included in the range of 0..

2条回答
  •  独厮守ぢ
    2021-01-13 17:42

    This seems too easy, am I understanding the problem correctly?

    \[01][0-9]{3}\
    

    I don't know what .. means, integer in range? That must be a perlism or something.

    This seems to work the way you want to me:

    In [3]: r = re.compile(r'[01][0-9]{3}')
    
    In [4]: r.match('0001')
    Out[4]: <_sre.SRE_Match object at 0x2fa2d30>
    
    In [5]: r.match('1001')
    Out[5]: <_sre.SRE_Match object at 0x2fa2cc8>
    
    In [6]: r.match('2001')
    
    In [7]: r.match('001')
    
    In [8]: 
    

提交回复
热议问题