Regex to optionally match tokens

Looking for help completing my regex. I’m looking to match two cases of import statements in code.

import package and
import module from package

My current regex matches on the latter, but i want to turn it into an optional query in case the former pattern is found without the from keyword immediately proceeding.

Here what i have:
import ({[^}]*})?.*from [a-z]+

>Solution :

Here’s the expression for your case:

^(?:import (?:(?:[a-zA-Z\_\-\.]+)|(?:\sfrom\s)(?:[a-zA-Z\_\-\.]+))+)

First part of the expression [a-zA-Z\_\-\.]+) will ensure if there is a package exist.

Then I have used OR operator because your expression can have also another syntax of import.

Second part of expression will ensure that there’s from keyword in your import and a package name exists too. And after package name there should not be any space or special character. You can customize it according to your needs.

Hope it helps.

?: used to remove groups.

Leave a Reply