Search code examples
pythonassert

How can i ignore the characters between brackets?


Example: The hardcoded input in the system:

Welcome to work {sarah} have a great {monday}! 

The one i get from an api call might differ by the day of the week or the name example:

Welcome to work Roy have a great Tuesday!

I want to compare these 2 lines and give an error if anything but the terms in brackets doesn't match.

The way I started is by using assert which is the exact function I need then tested with ignoring a sentence if it starts with { by using .startswith() but I haven't been successful working my way in specifics between the brackets that I don't want them checked.


Solution

  • Regular expressions are good for matching text.

    Convert your template into a regular expression, using a regular expression to match the {} tags:

    >>> import re
    
    >>> template = 'Welcome to work {sarah} have a great {monday}!'
    
    >>> pattern = re.sub('{[^}]*}', '(.*)', template)
    >>> pattern
    'Welcome to work (.*) have a great (.*)!'
    

    To make sure the matching halts at the end of the pattern, put a $:

    >>> pattern += '$'
    

    Then match your string against the pattern:

    >>> match = re.match(pattern, 'Welcome to work Roy have a great Tuesday!')
    >>> match.groups()
    ('Roy', 'Tuesday')
    

    If you try matching a non-matching string you get nothing:

    >>> match = re.match(pattern, 'I wandered lonely as a cloud')
    >>> match is None
    True
    

    If the start of the string matches but the end doesn't, the $ makes sure it doesn't match. The $ says "end here":

    >>> match = re.match(pattern, 'Welcome to work Roy have a great one! <ignored>')
    >>> match is None
    True
    

    edit: also you might want to escape your input in case anyone's playing silly beggars.