Python Regular Expression; replacing a portion of match

前端 未结 4 1268
时光说笑
时光说笑 2020-12-22 00:04

How would I limit match/replacement the leading zeros in e004_n07? However, if either term contains all zeros, then I need to retain one zero in the term (see example below

4条回答
  •  鱼传尺愫
    2020-12-22 01:06

    edit: Don't let anybody talk you out of validating the format of the fixed data. If that's what you need, don't settle for something overly simple .

    Not very pretty, but in a situation that seems fixed, you can just
    set all the permutations, then blindly capture the good parts,
    leave out the zero's then substitute it all back.

    Find ([a-z])(?:([1-9][0-9][0-9])|0([1-9][0-9])|00([1-9]))(_[a-z])(?:([1-9][0-9])|0([1-9]))

    Replace $1$2$3$4$5$6$7

    Expanded

     ( [a-z] )                     # (1)
     (?:
          ( [1-9] [0-9] [0-9] )         # (2)
       |  
          0
          ( [1-9] [0-9] )               # (3)
       |  
          00
          ( [1-9] )                     # (4)
     )
     ( _ [a-z] )                   # (5)
     (?:
          ( [1-9] [0-9] )               # (6)
       |  
          0
          ( [1-9] )                     # (7)
     )
    

    Output

     **  Grp 0 -  ( pos 0 , len 8 ) 
    e004_n07  
     **  Grp 1 -  ( pos 0 , len 1 ) 
    e  
     **  Grp 2 -  NULL 
     **  Grp 3 -  NULL 
     **  Grp 4 -  ( pos 3 , len 1 ) 
    4  
     **  Grp 5 -  ( pos 4 , len 2 ) 
    _n  
     **  Grp 6 -  NULL 
     **  Grp 7 -  ( pos 7 , len 1 ) 
    7  
    

提交回复
热议问题