Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading