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 – how to find multiple import statement matches

I’m trying to find all occurrences of a js import statement in a string of text

For example in this string:

import $ from "./components/jquery.js"; import dirtyFormUnload from "./components/dirtyFormUnload.js";

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

I’d like to match

import $ from "./components/jquery.js";

and

import dirtyFormUnload from "./components/dirtyFormUnload.js";

The regex I’ve put together is below, but it matches the entire string once, instead of each individual import statement

import\s+.*\s+from\s+['""].*\.js[^\s;]*[\s;]?

>Solution :

your regex statement is getting greedy, meaning that the first .* is matching as much as it can, including the next input statement. One way to fix this is to prevent it from matching ; characters like this:

import\s+[^;]*\s+from\s+['""][^;]*\.js[^\s;]*[\s;]?
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