Home  >  Article  >  Backend Development  >  正则 匿名捕获 命名捕获

正则 匿名捕获 命名捕获

WBOY
WBOYOriginal
2016-06-06 20:32:551444browse

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

<code>$str = 'Mr.Ck-@139.com';

if(preg_match('(?:[a-zA-Z0-9_-.]+)@(?:[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);
}
</code>

错误提示

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

回复内容:

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

<code>$str = 'Mr.Ck-@139.com';

if(preg_match('(?:[a-zA-Z0-9_-.]+)@(?:[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);
}
</code>

错误提示

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 的第一个参数为正则的字符串, 正则需要开始和结束标记你这里没有.
<code>'(?:[a-zA-Z0-9_-.]+)@(?:[a-zA-Z0-9_-.]+)'
(?[0-9]+)(.(?[0-9]+))*
</code>

改为

<code>'/(?:[a-zA-Z0-9_-.]+)@(?:[a-zA-Z0-9_-.]+)/'
'/(?[0-9]+)(.(?[0-9]+))*/'
</code>
  • 上面的改了之后还是错误的, 错误的原因在于:

    • _-. 中括号内的 - 线是有特殊含义的(请参考a-z, 0-9).
    • 第二个正则中 (? 这样的写法是不正确的, PHP 的报错信息为:
      Warning: preg_match(): Compilation failed: unrecognized character after (? or (?- at offset 2 in T:\1.php on line xx 因为不知道你第二个具体要做啥, 可以直接删除 ? 号, 或者在 ? 号后面加上 : 号解决报错的问题.

附改后的代码:

<code>php</code><code><?php $str = 'Mr.Ck-@139.com';

if(preg_match('/(?:<#user>[a-zA-Z0-9_\-.]+)@(?:[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);
}
</code>

号码 最终问题 我解决了

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn