简体   繁体   中英

Python - re.search and/or re.finditer not matching simple pattern

I have the following simple search on a block of text retrieved from a database:

    pattern = r"%quiz%"
    lesson_pieces = []
    if re.search(pattern, lesson.lesson_text) is not None:
        lesson_piece_indices =  [m.start() for m in re.finditer(pattern,lesson.lesson_text)]

The complete code splits the text into segments based on the string %quiz% appearing in the text. and the view then displays a segment and requires the user to take an action to see the next segment. However when I run this code the text is not split into segments, instead it does not seem to find the pattern and returns the entire text string. Here is a snippet of some sample text:

Visible tattoos are not permitted. You must be able to cover up the tattoo. Neck and facial tattoos are not allowed. Tattoos on hands must be covered while working.

%quiz%

If you chose to arrive in or change out...

When displayed, what should show is:

Visible tattoos are not permitted. You must be able to cover up the tattoo. Neck and facial tattoos are not allowed. Tattoos on hands must be covered while working.

Click to Continue...

Instead the complete text from above shows including %quiz% which if it had been found would have been extracted out. What am I missing here?

I solved this problem using kindall's suggestion in a comment , changing the code to:

lesson_pieces = lesson.lesson_text.split("%quiz%")

The .split was exactly what I needed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM