[Python] Limiting the scope of re.sub [duplicate]

Discussão em 'Python' iniciado por Stack, Setembro 13, 2024.

  1. Stack

    Stack Membro Participativo

    Suppose I have a long 'mystring' and I have already removed all of its line feeds.

    startpattern some unneeded data endpattern Juicy Data Block 1 startpattern more unneeded data endpattern Juicy Data Block 2


    I want to use re.sub to grab both Juicy Data Blocks

    re.sub(r'startpattern.+endpattern','',mystring)


    but of course the problem is the greedy lookahead will remove the first section of data I need, only leaving the Juicy Data Block 2 section. Adding a count=1 argument to the re.sub doesn't solve the greedy lookahead. How to best go about capturing all the data I need? Should I be splitting instead of the startpattern.+endpattern bookends and operating on sections or can re.sub do this?

    Continue reading...

Compartilhe esta Página