简体   繁体   中英

find all imported file names from a source file with regexp javascript

i am new to regex and javascript.
i am trying to create an array of all imported files of a source file using regex.
before an import statement there will be a '@' sign as well. for example:

if the file looks like

...
@import file1,file2, file3;
int i=6;
@import file4;
...

then i need an array with [file1,file2,file3,file4]

so far i have tried to create the reg exp itself with no success.
any help with that ?
Thanks edited to make things more clear

You can use String.prototype.split() with RegExp /@import|,|;|\\s/ , Array.prototype.filter() with parameter Boolean

text.split(/@import|,|;|\s/).filter(Boolean)

plnkr http://plnkr.co/edit/OpLBFMehRjC1sm1GA9BL?p=preview

Complex solution for your question (+demo):

 function run() { var re = /(?:@import)\\s+([^;]+)/igm, str = document.getElementById('demo').value, arr = []; while (result = re.exec(str)) { arr = arr.concat(result[1].split(/[,\\s]+/)) } //console.log(arr); document.getElementById('result').innerHTML = JSON.stringify(arr); } 
 <p> <textarea id="demo" cols="50" rows="15"> // ..... @import file1,file2, file3; int i=6; @import file4; // ..... </textarea> </p> <p> <span id="result" style="color:green;"></span> </p> <p> <input type="button" value="RUN" onclick="run()"> </p> 

Run my demo, to see the result.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM