[Python] How to a match any sequence of text until "#{" in pyparsing

Discussão em 'Python' iniciado por Stack, Fevereiro 12, 2025.

  1. Stack

    Stack Membro Participativo

    I want to do string templating with py parsing. I have failed multiple times to define a grammar that can parse a string with inserted text inbetween "#{" and "}" (seems pretty basic) :

    Example of grammar which doesn't work :

    from pyparsing import CharsNotIn, FollowedBy, Group, Literal, OneOrMore, Suppress
    # Define the unwanted sequence
    hash_tag = Suppress(Literal('#{')) + CharsNotIn('}') + Suppress(Literal('}'))
    text_part = CharsNotIn('#{')
    # Combine the parts to match the entire string
    parser = OneOrMore(Group(hash_tag) | text_part)
    test_string = "Some text \n with a stranded # and a stranded { then a correct #{ insertion of \n some # other text } and then some text"

    result = parser.searchString(test_string)
    expected_result = ["Some text \n with a stranded # and a stranded { then a correct ",[" insertion of \n some # other text "]," and then some text"]
    print(result)


    The result is not the expected result (I get ["Some text \n with a stranded "])

    Continue reading...

Compartilhe esta Página