Search code examples
regexpython-3.xpyautogui

python regular expression to divide a string


I need to split a string like this:

{tab 3}1/*{tab}*/30116{tab}2012{tab, 2}01{tab}{2016}enter

I want to separate the parts that are in and out of { and }

The idea is to make a text interpreter for commands to be passed to python pyautogui.

The result should be in order, perhaps a list with commands and strings.

[ 'tab, 3', '130116', 'tab', '2012', 'tab, 2', '01', 'tab', '2016', 'enter']

The order is important. Using Regex Tester I do this pattern:

re.compile (ur '(\{(|.)*\})', re.MULTILINE | re.IGNORECASE)

This marks all parts between { and }. But I'm not knowing how to extract or split the string.

The part between /* and */ I am already removing correctly before getting this part. They can ignore it.

If possible, I would like a Pythonic way to solve this. I'm starting in python, for this, I must have skipped the solution.

If there are any mistakes, forgive me. I'm from Brazil.

If there some other interpreter already, please show me.

Thanks in advance.

Alexandre

Translated by Google translator.


Solution

  • I understand comments will be filtered out already so I'm proposing a simple solution, not sure it's the most "pythonic" but pythonic enough and easy to get a hold of.

    You can use re.split according to {} chars and then remove the empty strings with a call to filter out the empty strings.

    import re
    
    r="{tab 3}130116{tab}2012{tab, 2}01{tab}{2016}enter"
    
    z = filter(lambda x : x!="",re.split("[{}]",r))
    
    print(z)
    

    output:

    ['tab 3', '130116', 'tab', '2012', 'tab, 2', '01', 'tab', '2016', 'enter']
    

    (there may be other ways of doing it without the filter part with regex, more complex)