[Python] Regex to match only book('knjiga') with specific name('naslov')

Discussão em 'Python' iniciado por Stack, Julho 16, 2025.

  1. Stack

    Stack Membro Participativo

    I have a simple xml:

    <?xml version="1.0" encoding="utf-8" ?>
    <book_list>
    <book rbr="1" >
    <title> Yacc </title>
    <author> Filip Maric </author>
    <year> 2004 </year>
    <publisher> Matematicki fakultet </publisher>
    <price currency="din"> 100 </price>
    </book>
    <book rbr="2" >
    <author> Fredrik Lundh </author>
    <price currency="eur"> 50 </price>
    <publisher> O’Reilly & Associates </publisher>
    <year> 2001 </year>
    <title> Python Standard Library </title>
    </book>
    </book_list>


    I need to match a book with a specific name with regex in Python. I can easily match any book with:

    r'<book\s*rbr="\d+"\s*>.*?</book>'

    (single line mode on), and then check if it is the right one, but if I want to match specific book - e.g., Python Standard Library, direct with regex, I can't get it right. If I try

    r'<book\s*rbr="\d+"\s*>(?P<book>.*?<title> Python Standard Library </title>.*?)</book>'

    , with single line mode on, it will match everything from the beginning and I understand why but I couldn't find the way to match only one book tag. I tried all lookups and all different modes without success.

    What is the right way to do it, that will work for any number of books in book_list?

    Continue reading...

Compartilhe esta Página