[Python] Regex backreferences -- yet another use

Previously (Ctrl-F: "SAT solver on top of regex matcher").

Writing x=x+1 in code is too oldschool and verbose, but Python doesn't support C-style increment/decrement. It however supports statements like x+=1.

The following code can be used to find such statements and maybe even replace them:

#!/usr/bin/env python3
import re, sys

for line in sys.stdin:
    line=line.rstrip()
    m=re.match(r"(.*)([a-z0-9_]+)=\2\+(.*)", line)
    if m!=None:
        print ("replace", m[0])
        print ("to     ", m[1]+m[2]+"+="+m[3])

Real data from my ToyTLS code:

replace     s=s+": "+alert_type_s[err]
to          s+=": "+alert_type_s[err]
replace     cur_seq_n_to_serv=cur_seq_n_to_serv+1
to          cur_seq_n_to_serv+=1
replace         buf=buf+got
to              buf+=got
replace         all_certs=all_certs+certs
to              all_certs+=certs
replace             tmp=tmp+struct.pack("<BB", H, L)
to                  tmp+=struct.pack("<BB", H, L)
replace     tmp=tmp+b"\x00\x0b\x00\x04\x03\x00\x01\x02"
to          tmp+=b"\x00\x0b\x00\x04\x03\x00\x01\x02"

Vim/Emacs fans can easily create a script for that, I suppose.

Update 20240519 18:50:10 EEST:

Vim search string:

/\([a-z0-9_]\+\)=\1+

Using grep against my ToySSH v4:

% cat toyssh_v4.py | grep '\([a-zA-Z0-9_]\+\)=\1+'
...
KEX_ALGOS=KEX_ALGOS+"diffie-hellman-group1-sha1"
CIPHER_ALGOS=CIPHER_ALGOS+"none"
MAC_ALGOS=MAC_ALGOS+"hmac-sha2-256,"
SERVER_HOST_ALGOS=SERVER_HOST_ALGOS+"rsa-sha2-256,"
SERVER_HOST_ALGOS=SERVER_HOST_ALGOS+"ssh-dss"
            idx=idx+1
            idx=idx+2
    pkt_len=pkt_len+MAC_SIZE
    recv_seqno=recv_seqno+1
    serv_to_client_ctr=serv_to_client_ctr+blocks_total
    recv_seqno=recv_seqno+1
    send_seqno=send_seqno+1
    idx=idx+0x10
    idx=idx+1
            padlen=padlen+16
    buf=buf+cookie
    buf=buf+pack_str(encryption_algorithms_server_to_client)
...

(UPD: 20240617 15:25:12 CEST: As seen on reddit.)

(the post first published at 20240514, updated 20240519.)


List of my other blog posts.

Subscribe to my news feed,

Yes, I know about these lousy Disqus ads. Please use adblocker. I would consider to subscribe to 'pro' version of Disqus if the signal/noise ratio in comments would be good enough.