Sublime Forum

Parse Python import/from

#1

Hello. I can use the ST-API ‘find_all’ method to locate ‘import’ or ‘from’ statements from a Python file. I want to then use regex to extract the library names. For example:

import lib1, lib2 from lib3 import type3 import lib4 as bob from lib5 import ted as edward, dave as david

I want to obtain ‘lib1’, ‘lib2’, but I also want ‘lib3’ together with ‘type3’; that is, to be able to consider them as a paired-item.

Firstly, how can I grab ‘lib1’ and ‘lib2’? I’m hoping a regex-whiz can point me in the right direction :smile:

0 Likes

#2

I realised I don’t need to do this with regex - I can use the string function split(), tuples, list comprehension, etc. to break out the bits I need.

If I want to achieve a similar thing in the tmLanguage file - that is, to scope the words after import/from (but differently according to their purpose) - then this would be more complicated :wink: . I would need to ‘end’ at either the end-of-line or a comment mark, and use recursion.

0 Likes