Python : Remove sequences of brackets and the content inside it if they are only at the end of a string

Viewed 47

I want to remove brackets and what is inside only if they are at the end of the string. Let's take three exemples :

s1 = 'BkToCstmrStmt/Stmt/Ntry[2]/NtryDtls/TxDtls/RltdPties/Cdtr/PstlAdr/AdrLine[2][]'
s2 = "BkToCstmrStmt/Stmt/Ntry[2]/AmtDtls/InstdAmt/Amt['CHF']"
s3 = "BkToCstmrStmt/Stmt/Bal[1]/Amt['CHF']"

I want to get

s1 = 'BkToCstmrStmt/Stmt/Ntry[2]/NtryDtls/TxDtls/RltdPties/Cdtr/PstlAdr/AdrLine'
s2 = "BkToCstmrStmt/Stmt/Ntry[2]/AmtDtls/InstdAmt/Amt"
s3 = "BkToCstmrStmt/Stmt/Bal[1]/Amt"

Here is what I tried :

name_parts = re.findall(r'[^\W_]+|[\W_]+', s3)

print(name_parts)

lenght = len(name_parts) - 1
    # we want to analize the last element of the list, if it contains '_-'
if lenght >= 0:  # it is to prevent an error if we have '' so an dimension '-1'
        # We do a loop while to test if the parts have '-_', if true we execute the loop
        # until it is false
    while re.match('[^A-Za-z/]', name_parts[lenght]) or re.match('[^A-Za-z/]', name_parts[lenght-1]) :
            # if it is true it will remove them
            name_parts[lenght] = ''  # it will remove them
            print(name_parts)
            lenght -= 1  # if the condition was true, we continue with one inferior part
else:
    pass

new_string = ''.join(map(str, name_parts))  # now that we have cleaned if it was necessary
    # we concatenate them

But It does not work. Anyone has an idea to efficiently do that ?

2 Answers

Regex101:

import re

s1 = 'BkToCstmrStmt/Stmt/Ntry[2]/NtryDtls/TxDtls/RltdPties/Cdtr/PstlAdr/AdrLine[2][]'
s2 = "BkToCstmrStmt/Stmt/Ntry[2]/AmtDtls/InstdAmt/Amt['CHF']"
s3 = "BkToCstmrStmt/Stmt/Bal[1]/Amt['CHF']"

for s in [s1, s2, s3]:
    s = re.sub(r'(\[[^]]*\])+$', '', s)
    print(s)

Prints:

BkToCstmrStmt/Stmt/Ntry[2]/NtryDtls/TxDtls/RltdPties/Cdtr/PstlAdr/AdrLine
BkToCstmrStmt/Stmt/Ntry[2]/AmtDtls/InstdAmt/Amt
BkToCstmrStmt/Stmt/Bal[1]/Amt

Here's a non-regex approach:

s1 = 'BkToCstmrStmt/Stmt/Ntry[2]/NtryDtls/TxDtls/RltdPties/Cdtr/PstlAdr/AdrLine[2][]'
s2 = "BkToCstmrStmt/Stmt/Ntry[2]/AmtDtls/InstdAmt/Amt['CHF']"
s3 = "BkToCstmrStmt/Stmt/Bal[1]/Amt['CHF']"

for s in (s1, s2, s3):
    while s.endswith(']'):
        s = s[:s.rfind('[')]
    print(s)

Prints

BkToCstmrStmt/Stmt/Ntry[2]/NtryDtls/TxDtls/RltdPties/Cdtr/PstlAdr/AdrLine
BkToCstmrStmt/Stmt/Ntry[2]/AmtDtls/InstdAmt/Amt
BkToCstmrStmt/Stmt/Bal[1]/Amt
Related