简体   繁体   中英

How can I get the application names from an npm install command using a RegEx?

I have this string:

npm install lodash hapi thinky when  

I have this regex:

npm install ([\w\.\-]+)@?([0-9_\.\-\^]*)

But it only returns the first app name lodash . Which regex can I use to get lodash, hapi, thinky, when as a result?

You can use this regex:

npm install ((?:(?:[\w\.\-]+)@?(?:[0-9_\.\-\^]*)\s*)+)

This basically captures the whole thing after npm install into group 1. Then you can split this by \\s+ :

 var regex = /npm install ((?:(?:[\\w\\.\\-]+)@?(?:[0-9_\\.\\-\\^]*)\\s*)+)/g; var match = regex.exec("npm install lodash hapi thinky when"); var group1 = match[1]; console.log(group1.split(/\\s+/));

You can match npm install from the start of the string and then use an alternation to capture in a group one or more times a word character.

^npm install|(\\w+)

Regex demo

If you want to match more than a word character, you could use a character class and add the characters you want to match for example ([\\w.-]+)

 const regex = /^npm install|(\\w+)/g; const str = `npm install lodash hapi thinky when`; let m; let result = []; while ((m = regex.exec(str)) !== null) { if (m.index === regex.lastIndex) { regex.lastIndex++; } if (m[1]) { result.push(m[1]); } } console.log(result);

I wouldn't use a regex here. You can do something simple as this:

 const input = "npm install lodash hapi thinky when"; const output = input.slice(11).trim().split(/\\s+/); console.log(output);

Can use Regex to get the things you need! Follow my method:

 var str="npm install lodash hapi thinky when"; var regex = /(?<=(npm install ([A-Za-z_ \\.]*)))(\\w+)(?=([A-Za-z_ \\.]*))/g; var match = str.match(regex); console.log(match);

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