Python regex to match all words in {}
Question: I need regex in python to get all words that are in {} for example

    
    
    a = 'add {new} sentence {with} this word'
    

Result with re.findall should be [new, with]

Thanks


Answer: Try this:

    
    
    >>> import re
    >>> a = 'add {new} sentence {with} this word'
    >>> re.findall(r'\{(\w+)\}', a)
    ['new', 'with']
    

Another approach using `Formatter`:

    
    
    >>> from string import Formatter
    >>> a = 'add {new} sentence {with} this word'
    >>> [i[1] for i in Formatter().parse(a) if i[1]]
    ['new', 'with']
    

Another approach using `split()`:

    
    
    >>> import string
    >>> a = 'add {new} sentence {with} this word'
    >>> [x.strip(string.punctuation) for x in a.split() if x.startswith("{") and x.endswith("}")]
    ['new', 'with']
    

You can even use `string.Template`:

    
    
    >>> class MyTemplate(string.Template):
    ...     pattern = r'\{(\w+)\}'
    >>> a = 'add {new} sentence {with} this word'
    >>> t = MyTemplate(a)
    >>> t.pattern.findall(t.template)
    ['new', 'with']
    

