正则 匿名捕获 命名捕获


深知正则表达式的威力最近学习一些,偶遇问题,废话不多说上代码:


 $str = '[email protected]';

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这个函数的什么机制导致的把?

php

lidun 8 years, 10 months ago

号码 最终问题 我解决了

kukulza answered 8 years, 10 months ago

  • 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


 <?php

$str = '[email protected]';

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);
}

百合吧G answered 8 years, 10 months ago

Your Answer