-
-
Save manekinekko/7e58a17bc62a9be47172 to your computer and use it in GitHub Desktop.
let regex = `import | |
(?: | |
["'\s]* | |
([\w*{}\n, ]+) | |
from\s* | |
)? | |
["'\s]* | |
([@\w/_-]+) | |
["'\s]* | |
;? | |
`; | |
// Matches... | |
/* | |
import { | |
Component | |
} from '@angular2/core'; | |
import defaultMember from "module-name"; | |
import * as name from "module-name "; | |
import { member } from " module-name"; | |
import { member as alias } from "module-name"; | |
import { member1 , member2 } from "module-name"; | |
import { member1 , member2 as alias2 , member3 as alias3 } from "module-name"; | |
import defaultMember, { member, member } from "module-name"; | |
import defaultMember, * as name from "module-name"; | |
import "module-name"; | |
*/ | |
Hey everyone,
I wanted to share an optimized regex pattern that can be used to match import statements in JavaScript. This regex will successfully match various types of imports, including side effect imports (e.g., import "module-name";
) and dynamic imports. It also handles different types of quotes, multiline import statements, and multiple whitespaces.
Here's the optimized regex pattern:
import\s+(?:{[^{}]+}|.*?)\s*(?:from)?\s*['"].*?['"]|import\(.*?\)
You can check out a live demo and test it using this Regex101 link.
Hey everyone,
I wanted to share an optimized regex pattern that can be used to match import statements in JavaScript. This regex will successfully match various types of imports, including side effect imports (e.g.,
import "module-name";
) and dynamic imports. It also handles different types of quotes, multiline import statements, and multiple whitespaces.Here's the optimized regex pattern:
import\s+(?:{[^{}]+}|.*?)\s*(?:from)?\s*['"].*?['"]|import\(.*?\)You can check out a live demo and test it using this Regex101 link.
I love it! Thanks for sharing!
thanks @ganeshkbhat, I used it for the reference. Mine particular case to find occurences of specific import package.
import(?:[\s.*]([\w*{}\n\r\t, ]+)[\s*]from)\s+['"]lodash['"];
^^^^^^
thank you for sharing this publically. is there a final version of the expression. I see all links have some or the other bug and has been worked on for many use cases but there is one of the other bug. i feel a duh here. i accumulated all the use cases now of the links.
i wish to get the
---objects---
and---modules---
from the following as a final match access:import
---objects---
from "---modules---
"let variable = import("
---modules---
")The regex
/import(?:[\s.*]([\w*{}\n\r\t, ]+)[\s*]from)?[\s*](?:["'](.*[\w]+)["'])?/gm
matches all https://regex101.com/r/QtftIb/1 other than:second, can i use this for my intented requirement?