简体   繁体   English

正则表达式多匹配字符串

[英]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. (以粗体显示)是我要匹配的内容,第1组是关键字,第2组是搜索值,该值是可选的。

npm start search npm开始搜索

npm start search = test-string npm开始搜索 = 测试字符串

npm start search =" test " npm开始搜索 =“ 测试

npm start search =' test ' npm start search =' 测试 '

npm start search =" test, test-string " npm start search =“ 测试,测试字符串

npm start search =' test,test ' npm start search =' 测试,测试 '

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. 在演示中,我删除了字符串中的引号,因为它们是由Shell解析的,而不是传递给npm的。 I also had to put \\n in the [^] so it wouldn't match across multiple lines. 我还必须将\\n放在[^]这样它就不会在多行中匹配。

Try this : 尝试这个 :

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

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

The following should give you the flag and value aftr stripping the quotes from the value: 以下应该为您提供标志和值aftr,从值中删除引号:

 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 如果您不需要匹配npm start只需简单地npm start

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

Haven't tested yet might need more tweaking. 尚未测试,可能需要更多调整。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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