2013-02-14 38 views
0

我想我一直在看這太久。 我似乎無法得到這個正則表達式的工作。正則表達式失敗,我看不出爲什麼

代碼:

$pattern='/([0-9A-Z\-])*(#)(\s*)/i'; 

if (preg_match($pattern,'B-25-1abc-SW-19# ',$matches)) { 
    echo $matches[0]; 
} 

(從評論):
我期待它打印出來B-25-1abc-SW-19#文本,但它不打印任何東西,因爲它不進入if語句的真正部分。

我也試圖改變格局的樣子:

$pattern='/^$([0-9A-Z\-])*(#)(\s*)/i'; 

但是,這並沒有任何固定它。

+1

你期望它做什麼?它有什麼作用? – 2013-02-14 16:19:45

+0

我期待它打印出B-25-1abc-SW-19#文字......但它不打印任何東西......沒有匹配...... – dot 2013-02-14 16:20:43

+0

如果它與其他東西匹配,它不應該匹配_這是因爲你需要在我的測試中用'^ $' – 2013-02-14 16:20:54

回答

1

你可能放錯位置的量詞(儘管它應該將整個字符串仍然匹配):

$pattern='/([0-9A-Z\-])*(#)(\s*)/i'; 

應該是:

$pattern='/([0-9A-Z\-]*)(#)(\s*)/i'; 

如果真的只是matches[0]你後,你應該檢查你的原始字符串,也許你的-有一些utf8字符,它不是你模式中的減號字符(或其他方式)。

+0

除非$ 1捕獲組被訪問。 – 2013-02-14 16:22:51

+0

@Michael Berkowski確實,但我猜測這就是OP之後的事情。正則表達式應該匹配'matches [0]'的地方,所以這是我可以看到的一個可能的問題。 – jeroen 2013-02-14 16:24:19

+0

如何測試utf8字符方案? – dot 2013-02-14 16:42:39

0

明星是第一後)代替] :)

  $pattern='/([0-9A-Z\-]*)(#)(\s*)/i'; 

      $matches= array(); 
      if (preg_match($pattern,'B-25-1abc-SW-19# ',$matches)) { 
       print_r($matches); 
      } 

//N.B. 
//http://php.net/manual/en/function.preg-match.php 
//If matches is provided, then it is filled with the results of search. $matches[0] will contain the text that matched the full pattern, $matches[1] will have the text that matched the first captured parenthesized subpattern, and so on. 
相關問題