2015-09-06 30 views
1

我正在使用的sscanfsscanf的正則表達式與匹配甚至是空字符串

sscanf($seat, "%d-%[^(](%[^@]@%[^)])"); 

這個表達式,而且運作良好時,我得到這樣的字符串: 173-9B([email protected] [email protected]) 但是當我得到這個一種字符串: 173-9B(@3.14 [email protected])

這一切都搞砸了,我怎麼也接受第一(和第一@之間空字符串?

+0

使用sscanf而不是'preg_match'的任何原因? – anubhava

+0

@anubhava不是特別的,只是對我來說更方便。 – Dano

回答

1

你會使用一個正則表達式中preg_match來處理輸入可選的數據存在會更好:

$re = '/(\d*)-([^(]*)\(([^@]*)@([^)]*)\)/'; 

preg_match($re, '173-9B(@3.45 [email protected])', $m); 
unset($m[0]); 
print_r($m); 

輸出:

Array 
(
    [1] => 173 
    [2] => 9B 
    [3] => 
    [4] => 3.45 [email protected] 
) 

而示例2:

preg_match($re, '173-9B([email protected] [email protected])', $m); 
unset($m[0]); 
print_r($m); 

Array 
(
    [1] => 173 
    [2] => 9B 
    [3] => AA 
    [4] => 3.45 [email protected] 
) 

使用([^@]*)將使其匹配0個不是@的字符。

相關問題