Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex python compressing string

Tags:

python

regex

I have a file like the one below-

I want to print the fist and last occurence of every common substring so -\imm_pt_z4a[0], \imm_pt_z4a[1] becomes \imm_pt_z4[0:1]

mod pez(ck2_imm_z4a, ck2_lt_func_z4a, ck2_or0_z4a, ck2_opr1_z4a, 
        ck2_oprk_z4a, ck2_oprl_z4a, ck2_oprm_z4a, ck2_wtn_z404a, 
        ck2_wtx_z404a, \imm_pt_z4a[0] , \imm_pt_z4a[1] , ldimm_z42b_b, 
        lt_anden_z4a, \lt_imm_z4a_b[0] , \lt_imm_z4a_b[1] , 
        \lt_imm_z4a_b[2] , \lt_imm_z4a_b[3] , \lt_imm_z4a_b[4] , 
        \lt_imm_z4a_b[5] , \lt_imm_z4a_b[6] , \lt_imm_z4a_b[7] , 
        \lt_imm_z4a_b[8] , \lt_imm_z4a_b[9] , \lt_imm_z4a_b[10] ,
        \or0_z42b_b[0] , \or0_z42b_b[1] , \or0_z42b_b[2] , 
        \or0_z42b_b[3] , \or0_z42b_b[4] , \or0_z42b_b[5] , 
        \or0_z42b_b[6] , \or0_z42b_b[7] , \or0_z42b_b[8] ,

I am trying this regex

(\b[^\\;]+)\\([^[]+)\[(\d+)\][^;]+\2\[(\d+)\]

using this to substitute

\1\2[\3:\4]

https://regex101.com/r/vT3xC1/2

The first group is always found correctly but the next group of strings i always miss the first one so output is

mod pecl (ck2_imm_z4a, ck2_lt_func_z4a, ck2_or0_z4a, ck2_opr1_z4a, 
    ck2_oprk_z4a, ck2_oprl_z4a, ck2_oprm_z4a, ck2_wtn_z404a, 
    ck2_wtx_z404a, ldimm_z42b_b, 
    lt_anden_z4a, lt_imm_z4a_b[0:31] , 
    \lt_result_z4a[0] , lt_result_z4a[1:63] ,\lt_tbl_z4a[0] , lt_tbl_z4a[1:10] , 

It should have been

mod pecl (ck2_imm_z4a, ck2_lt_func_z4a, ck2_or0_z4a, ck2_opr1_z4a, 
    ck2_oprk_z4a, ck2_oprl_z4a, ck2_oprm_z4a, ck2_wtn_z404a, 
    ck2_wtx_z404a, ldimm_z42b_b, 
    lt_anden_z4a, lt_imm_z4a_b[0:31] , 
    \lt_result_z4a[0:63] ,\lt_tbl_z4a[0:10] ,

Notice how the last line i get is->

\lt_result_z4a[0] , lt_result_z4a[1:63] ,\lt_tbl_z4a[0] , lt_tbl_z4a[1:10] ,

What I should have got is

\lt_result_z4a[0:63] ,\lt_tbl_z4a[0:10] ,

Really appreciate any help for fixing this.

like image 693
Illusionist Avatar asked Jul 31 '26 04:07

Illusionist


1 Answers

Replace

(\\\w+)\[(\d+)\](?:\s*,\s*\1\[(\d+)\])+

with

\1[\2:\3]

Of course, \w is an assumption on my end, but it fits your sample.

(\\\w+)        # a backslash and at least one word character, into group 1
\[(\d+)\]      # multiple digits in square brackets, into group 2
(?:            #   start non-capturing group
  \s*,\s*      #   a comma surrounded by whitespace
  \1           #   same as group 1
  \[(\d+)\]    #   multiple digits in square brackets, into group 3  
)+             # end non-capturing group, repeat

Group 3 will contain the last number, even if it matched multiple times in between.

like image 159
Tomalak Avatar answered Aug 01 '26 20:08

Tomalak



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!