Search code examples
pythonarrayssubstringsquare-bracket

Remove elements in the square bracket of a string from Python


I am required to remove the elements within the square bracket of a string. However, I am unable to get the desired results.

Below is desired output I am required to get:

Example of the Output

[[apple].png -> [.png

[apple]].png -> ].png

[[apple]].png -> [].png

[an]apple[adaykeeps]]the[[doctor]away.png -> apple]the[away.png

Below are the methods I've used but was unable to get the required output:

Regex Method

file = re.sub(r'(\d*\D+\d*)\s+','',re.sub(r'{.+?#(\d+).\d+)}',r'(\1)',file));

SubString Method

openbracket = file.find('['); closebracket = file.find(']');

if len(file) > closebracket : file = file[0: openbracket:] + file[closebracket + 1::]


Solution

  • You can do this with regex; your regex needs to match a [ followed by some number of non [ or ] characters until a ], and replace that string with nothing:

    import re
    
    strings = ['[[apple].png', '[apple]].png', '[[apple]].png', '[an]apple[adaykeeps]]the[[doctor]away.png']
    
    for s in strings:
        name = re.sub(r'\[[^][]*\]', '', s)
        print(name)
    

    Output:

    [.png
    ].png
    [].png
    apple]the[away.png
    

    This code will replace [] with an empty string ``; if this is not the desired behaviour change the * in the regex to a +.