简体   繁体   中英

Regex multi match on string

I'm trying to match multiple values with one regular expression.

I want to extract the flag and the value if it's present, however I want to provide the ability to the user to type the flag in multiple different ways.

npm start search
npm start search=test-string
npm start search="test"
npm start search='test'
npm start search="test, test-string"
npm start search=' test,test '

I want to be able to dissect the flag and the value after = , after equal it can be just one word or multiple values separated by a comma in single or double quotes.

here's what I've tried

(^[^=]+)\=([^'"].*)?

(in bold) is what I'm trying to match, group 1 would be the keyword, and group 2 would be the search value which is optional.

npm start search

npm start search = test-string

npm start search =" test "

npm start search =' test '

npm start search =" test, test-string "

npm start search =' test,test '

I've tried using negative lookahead and behind but keep failing...

You need to make the = optional.

If you want to allow quotes around the value, but not include them in the second capture group, put the quotes before the capture group and make them optional. Then match anything except quotes inside the capture group.

^([^=\n]+)=?['"]?([^'"\n]*)

DEMO

In the demo I removed the quotes from the strings, since those are parsed by the shell and not passed to npm. I also had to put \\n in the [^] so it wouldn't match across multiple lines.

Try this :

(?<=npm start)([^=\n]+)(?:=?)(?:['"]+)?([^\n\'\"]+)?(?:[^\S\n]?)

https://regex101.com/r/i0aacp/10/

The following should give you the flag and value aftr stripping the quotes from the value:

 myStr.match (/^npm start ([^\s]+)\s*=?\s*(['"]?[^'"]+?['"]?)\s*?$/i)

Or with quotes

myStr.match (/^npm start ([^\s]+)\s*=?\s*([^\s]+)?\s*$/i)

If you don't need to match npm start simply

  myStr.match (/\s*([^\s]+)\s*=?\s*([^\s]+)\s*?$/i)

Haven't tested yet might need more tweaking.

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