Implement this function in Python; Vim's regex engine is slow and we're trying to avoid adding more VimScript code if we can avoid it.