pythontextpython-re

My regex in python doesn't match using re.search()


I'm trying to extract the substring $200 from this text:

Autorización 28 MAY 2024, 20:34 (hora de CDMX)


$200.oo Monto

Concept

I'm using the next method in a for:

monto = re.search('^[$][0-9]+', line in the text)

But it doesn't match.


Solution

  • You have a ^ in your regexp, which anchors it to the start of the string. From the re manual:

    ^ (Caret.) Matches the start of the string, and in MULTILINE mode also matches immediately after each newline.

    That's naturally no good if you want to find something in the middle of a string (unless you do actually want to find matches at new lines in the string, then set the flags=re.MULTILINE option, as shown above).

    Try

    re.search(r'[$][0-9]+', ...)
    

    instead (so no anchoring).