正则语法

2020-12-12  本文已影响0人  爱折腾的傻小子
正则表达式
匹配用户名称

基本匹配

元字符
点运算符 .
字符串
否定字符集
重复次数
星号 *
加号 +
问号 ?
{} 号
(...)特征标群
| 或运算符
转码特殊字符
锚点
^ 号
$ 号
简写字符集

零宽度断言 (前后预查)
?=... 正先行断言
?!... 负先行断言
?<=... 正后发断言
?<!... 负后发断言

标志
忽略大小写
全局搜索
多行修饰符

贪婪匹配与惰性匹配

?:... 非捕获
// 使用 (?:) 非捕获 
$result = preg_match('@^(?:http://)?([^/]+)@i', 'http://www.codercto.com/index.html', $matches);
dump($result, $matches);
/*
1
array:2 [
  0 => "http://www.codercto.com"
  1 => "www.codercto.com"
]
*/

// 不使用(?:) 非捕获区别
$result = preg_match('@^(http://)?([^/]+)@i', 'http://www.codercto.com/index.html', $matches);
dump($result, $matches);
/*
1
array:3 [
  0 => "http://www.codercto.com"
  1 => "http://"
  2 => "www.codercto.com"
]
*/

// 使用 (?:) 非捕获 
$result = preg_match('@industr(?:y|ies)@', 'British industry', $matches);
dump($result, $matches);
/*
1
array:1 [
  0 => "industry"
]
*/

// 不使用 (?:) 非捕获
$result = preg_match('@industr(y|ies)@', 'British industry', $matches);
dump($result, $matches);
/*
1
array:2 [
  0 =>"industry"
  1 => "y"
]
*/
上一篇 下一篇

猜你喜欢

热点阅读