我在从字符串解析参数时遇到了问题。
参数由以下内容定义:
所有这些参数都是一个长字符串,p.ex:
-a val1 ! -b val2 --other "string with crazy -a --test stuff inside" --param-with-dash val1 val2 -test value-with-dash ! -c -d ! --test
-编辑
也是--param value-with-dash
-结束编辑
这是我所能得到的最接近的:
https://regex101.com/r/3aPHzp/1
/(?:(?P<inverted>\!) )?(?P<names>\-{1,2}\S+)($| (?P<values>.+(?=(?: [\!|\-])|$)))/U
不幸的是,当谈到引号中的自由文本值时,它就会中断。当没有值的参数后面跟着下一个参数时。
(我试图解析iptables的输出-保存,以防您被插入。另外,也许我以前可以用另一种奇特的方式拆分字符串,以避免hugh正则表达式,但我没有看到)。
非常感谢您的帮助!
--最终解决方案--
>= 5.6
(?<inverted>!)?\s*(?<name>--?\w[\w-]*)\s*(?<values>(?:\s*(?:\w\S*|["'](?:[^"'\\]*(?:\\.[^"'\\]*)*)['"]))*)\K
演示:https://regex101.com/r/xSfgxP/1
PHP < 5.6
(?<inverted>\!)?\s*(?<=(?:\s)|^)(?<name>\-{1,2}\w[\w\-]*)\s+(?<value>(?:\s*(?:\w\S*|["'](?:[^"'\\]*(?:\\.[^"'\\]*)*)['"]))*)
发布于 2017-03-23 16:19:04
RegEx:
(?<inverted>!)?\s*(?<name>--?\w[\w-]*)\s*(?<values>(?:\s*(?:\w\S+|["'](?:[^"'\\]*(?:\\.[^"'\\]*)*)['"]))*)\K现场演示 (更新)
细目
(?<inverted> ! )? # (1) Named-capturing group for inverted result
\s* # Match any spaces
(?<name> --? \w [\w-]* ) # (2) Named-capturing group for parameter name
\s* # Match any spaces
(?<values> # (3 start) Named capturing group for values
(?: # Beginning of a non-capturing group (a)
\s* # Match any spaces
(?: # Beginning of a non-capturing group (b)
\w\S+ # Match a [a-zA-Z0-9_] character then any non-whitespace characters
| # Or
["'] # Match a qoutation mark
(?: # Beginning of a non-capturing group (c)
[^"'\\]* # Match anything except `"`, `'` or `\`
(?: \\ . [^"'\\]* )* # Match an escaped character then anyhthing except `"`, `'` or `\` as much as possible
) # End of non-capturing group (c)
['"] # Match qutation pair
) # End of non-capturing group (b)
)* # Greedy (a), end of non-capturing group (a)
) # (3 end)
\K # Reset allocated memory of all previously matched charactersPHP代码:
<?php
$str = '-a val1 ! -b val2 --custom "string :)(#with crazy -a --test stuff inside" --param-with-dash val1 val2 -c ! -d ! --test';
$re = <<< 'RE'
~(?<inverted>!)?\s*(?<name>--?\w[\w-]*)\s*(?<values>(?:\s*(?:\w\S+|["'](?:[^"'\\]*(?:\\.[^"'\\]*)*)['"]))*)\K~
RE;
preg_match_all($re, $str, $matches, PREG_SET_ORDER);
print_r(array_map('array_filter', $matches));输出:
Array
(
[0] => Array
(
[name] => -a
[2] => -a
[values] => val1
[3] => val1
)
[1] => Array
(
[inverted] => !
[1] => !
[name] => -b
[2] => -b
[values] => val2
[3] => val2
)
[2] => Array
(
[name] => --custom
[2] => --custom
[values] => "string :)(#with crazy -a --test stuff inside"
[3] => "string :)(#with crazy -a --test stuff inside"
)
[3] => Array
(
[name] => --param-with-dash
[2] => --param-with-dash
[values] => val1 val2
[3] => val1 val2
)
[4] => Array
(
[name] => -c
[2] => -c
)
[5] => Array
(
[inverted] => !
[1] => !
[name] => -d
[2] => -d
)
[6] => Array
(
[inverted] => !
[1] => !
[name] => --test
[2] => --test
)
)https://stackoverflow.com/questions/42980062
复制相似问题