Forum Archive

re.search only returning first match

jsguntzel

There's a .py script I use on my Macbook that I'm trying to fire up in Editorial. On my Macbook it returns every regex match, but in Editorial it's only returning the first match. I've never tried to run a Python script in Editorial. What am I missing? Here's the script as I'm running it in Editorial:

import editor
import console
import os
import re

console.clear()

text = (editor.get_text(), "r")

for highlights in text:
    m = re.search("(?<=(==)).+(?=(==))", highlights)
    if m: print str("=>"), str(m.group(0))

So grateful for any help!

omz

I assume this line:

text = (editor.get_text(), "r") # (1)

was originally something like this:

text = open(somefile, "r") # (2)

These actually do very different things.

In (2), text is an open file handle. This can be used in a for-loop to iterate over all lines in the file (you're reading the file line-by-line while you're iterating, so the variable name text is actually kind of misleading, as it never contains the full text of the file).

In (1), text is a tuple of two strings, the document text and "r", so your loop executes exactly twice. The "r" doesn't really serve any purpose here (it seems like a leftover from the open call), and to be able to iterate over the lines in a string in the same way as you do it with an open file, you have to split it manually.

Long story short, here's what you can do:

import editor
import console
import re

console.clear()

text = editor.get_text()

for line in text.splitlines():
    m = re.search("(?<=(==)).+(?=(==))", line)
    if m: print str("=>"), str(m.group(0))
jsguntzel

Thank you so much for this very helpful explanation. And for the work you do. My dive into Editorial is turning out to be the thing that pushes me into really learning Python, rather than just feeling around in the dark (which has been a good way to learn up to this point, but, as evidenced here, has its limitations.)

I'm very grateful for your time.