而是用引號雜耍的,採取遠遠優於APPR oach:使用條件正則表達式。
基本格式如下:
(?(1)foo|bar)
# Meaning: if group1 is set, use foo, otherwise bar as subpattern
您的要求,這可以歸結爲:
--(?P<key>\w+)=(")?(?P<value>(?(2)[^"]+|[^\s]+))
在PHP
代碼,並解釋,這看起來更美麗:
<?php
$string = 'helloworld --name=stretch --message="Hi there everyone"';
$regex = '~
--(?P<key>\w+)= # look for two dashes, capture every word character into the group "key"
(")? # look for double quotes and make the group (2) optional
(?P<value> # save the following to the group "value"
(?(2)[^"]+|[^\s]+) # if (2) is set, capture everything BUT a double quote
# else capture everything but a space (not allowed without quotes)
)
~x'; # verbose modifier
preg_match_all($regex, $string, $matches, PREG_SET_ORDER);
foreach ($matches as $match)
echo "Key: {$match['key']}, Value: {$match['value']}\n";
/* output:
Key: name, Value: stretch
Key: message, Value: Hi there everyone
*/
?>
看到這個演示ideone.com。
你甚至可以更進一步,允許單引號作爲分隔符,並有逃脫報價在你的價值觀像這樣:
--(?P<key>\w+)=
(['"])? # allow single or double quotes
(?P<value>
(?(2).+?(?<!\\)(?=\2) # if (2) is set, match everything lazily afterwards
# and make sure that what follows is the formerly captured quote
# make also sure that what precedes, is not a backslash (thus allowing escaped quotes)
|[^\s]+)
)
看到這個demo on regex101.com(從@SebastianProske劫持,對不起隊友: )。
來源
2016-03-12 21:06:29
Jan
有沒有逃脫引號字符串內的報價的可能性?如果不是,我想' - ([a-zA-Z] +)=([^「's] + |」[^「] *」|'[^'] *')'應該這樣做。 –
是的,我試圖讓它接受逃脫報價 –
對不起,但你怎麼逃脫報價? –