正則 匿名捕獲 命名捕獲

來源:互聯網
上載者:User
深知Regex的威力最近學習一些,偶遇問題,廢話不多說上代碼:

$str = 'Mr.Ck-@139.com';if(preg_match('(?:<#user>[a-zA-Z0-9_-.]+)@(?:<#host>[a-zA-Z0-9_-.]+)', $str, $match)) {    print_r($match);}$str = '123,456,78,90';if(preg_match('(?[0-9]+)(.(?[0-9]+))*', $str, $match)) {    print_r($match);}

錯誤提示

Warning: preg_match(): Unknown modifier '@' in D:\webServ\index.php on line 15

Warning: preg_match(): Unknown modifier '(' in D:\webServ\index.php on line 23

我不知道是不是因為PHP函數的問題,我相信這個運算式應該是沒問題的,只是preg_match這個函數的什麼機制導致的把?

回複內容:

深知Regex的威力最近學習一些,偶遇問題,廢話不多說上代碼:

$str = 'Mr.Ck-@139.com';if(preg_match('(?:<#user>[a-zA-Z0-9_-.]+)@(?:<#host>[a-zA-Z0-9_-.]+)', $str, $match)) {    print_r($match);}$str = '123,456,78,90';if(preg_match('(?[0-9]+)(.(?[0-9]+))*', $str, $match)) {    print_r($match);}

錯誤提示

Warning: preg_match(): Unknown modifier '@' in D:\webServ\index.php on line 15

Warning: preg_match(): Unknown modifier '(' in D:\webServ\index.php on line 23

我不知道是不是因為PHP函數的問題,我相信這個運算式應該是沒問題的,只是preg_match這個函數的什麼機制導致的把?

  • preg_match 的第一個參數為正則的字串, 正則需要開始和結束標記你這裡沒有.
'(?:<#user>[a-zA-Z0-9_-.]+)@(?:<#host>[a-zA-Z0-9_-.]+)'(?[0-9]+)(.(?[0-9]+))*

改為

'/(?:<#user>[a-zA-Z0-9_-.]+)@(?:<#host>[a-zA-Z0-9_-.]+)/''/(?[0-9]+)(.(?[0-9]+))*/'
  • 上面的改了之後還是錯誤的, 錯誤的原因在於:

    • _-. 中括弧內的 - 線是有特殊含義的(請參考a-z, 0-9).
    • 第二個正則中 (? 這樣的寫法是不正確的, PHP 的報錯資訊為:
      Warning: preg_match(): Compilation failed: unrecognized character after (? or (?- at offset 2 in T:\1.php on line xx 因為不知道你第二個具體要做啥, 可以直接刪除 ? 號, 或者在 ? 號後面加上 : 號解決報錯的問題.

附改後的代碼:

php[a-zA-Z0-9_\-.]+)@(?:<#host>[a-zA-Z0-9_\-.]+)/', $str, $match)) {    print_r($match);}$str = '123,456,78,90';if(preg_match('/([0-9]+)(.([0-9]+))*/', $str, $match)) {    print_r($match);}

號碼 最終問題 我解決了

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.