Sublime Forum

Find(pattern, ...) returns (-1, -1) instead of None?

#1

The documentation for view.find() says that it returns None if nothing is found:

view.find(pattern, start_point, <flags>)

Returns the first region matching the regex pattern, starting from start_point, or None if it can’t be found. The optional flags parameter may be sublime.LITERAL, sublime.IGNORECASE, or the two ORed together.

It actually returns Region(-1, -1), when nothing is found:

>>> sublime.active_window().active_view().find('^class', 0)
(785, 790)
>>> sublime.active_window().active_view().find('^xxx$', 0)
(-1, -1)

Is this expected, is the documentation incorrect?

Something else that can be source of bugs is the fact that a zero-length Region evaluates as false in an if expression:

>>> sublime.active_window().active_view().find('^$', 0)
(741, 741)

match = sublime.active_window().active_view().find('^$', 0)
if match:  # will evaluate to false because zero-length matched Region.
    print('found match')

The way you need to check if something was matched is:

match = sublime.active_window().active_view().find('^$', 0)
if match != Region(-1, -1):  
    print('found match')

Or if None was returned, as the documentation says:

match = sublime.active_window().active_view().find('^$', 0)
if match is not None:  
    print('found match')
0 Likes

#2
2 Likes