0

i'm trying to esssentially get any dynamic input from a python script, in this case its a simple file organizing script. I need to make sure that any instance of [ or ] is wrapped like this [[] []].

So naturally i tried replace but that just put brackets around all of the escape brackets(the escape brackets for using glob.glob)

That proved useless so now i turn to re.sub but i can't seem to find a pattern that will only replace [ or ] with its escape counterpart if the [ or ] has no brackets around it.

I have no idea if that makes sense to anyone but thats pretty much it, here is the messed up re pattern i've got so far, it doesn't like me.

pattern = r'[^\[]([\[])[^\]]'
3
  • One problem, how would you if a [ or ] is used for quoting or they should be quoted ? Commented Sep 20, 2013 at 13:51
  • This is for filenames so basically i just have to escape any square brackets for the purposes of using glob.glob, btw the code worked except i changed [$1] to [\1] after that it was perfect, thanks very much. Commented Sep 20, 2013 at 13:55
  • Not a solution, but Pyregex can help you in testing patterns out quickly. Commented Sep 20, 2013 at 14:18

1 Answer 1

3

I'd choose a solution using the higher-order feature of re.sub to handle tokens (tokenizing is common practice in parsing computer languages):

def replaceToken(match):
    token = match.group()
    if len(token) == 3:
        return token
    else:
        return '[' + token + ']'

re.sub(r'(\[\[\])|(\[\]\])|\[|\]', replaceToken, 'foo[[bar]bloh')

Or in one call, if you prefer that:

re.sub(r'(\[\[\])|(\[\]\])|\[|\]',
       lambda x: x.group() if len(x.group()) == 3
                           else '[' + x.group() + ']', 'foo[[]bar]bloh')

Results:

'foo[[bar]bloh' → 'foo[[][[]bar[]]bloh'
'foo[[]bar]bloh' → 'foo[[]bar[]]bloh'
Sign up to request clarification or add additional context in comments.

2 Comments

OK great, the problem is that I don't work with Python so I will ask you for a simple thing and if it worked I will give you my up vote. Could you test this string for me: hello[ from ab ] and this is working []] working so far [[] and what about [[[ or ]][[ ?
Returns hello[[] from ab []] and this is working []] working so far [[] and what about [[][[][[] or []][]][[][[] for me. This is what OP wants; I'm skeptic that what he wants makes sense. I guess a better solution would be to find out if the input already is "quoted" using brackets or not and depending on that a quoting should take place, but that's a little out of scope here.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.