Simple regex
Regex quick reference
[abc] A single character: a, b or c
[^abc] Any single character but a, b, or c
[a-z] Any single character in the range a-z
[a-zA-Z] Any single character in the range a-z or A-Z
^ Start of line
$ End of line
\A Start of string
\z End of string
. Any single character
\s Any whitespace character
\S Any non-whitespace character
\d Any digit
\D Any non-digit
\w Any word character (letter, number, underscore)
\W Any non-word character
\b Any word boundary character
(...) Capture everything enclosed
(a|b) a or b
a? Zero or one of a
a* Zero or more of a
a+ One or more of a
a{3} Exactly 3 of a
a{3,} 3 or more of a
a{3,6} Between 3 and 6 of a
options: i case insensitive m make dot match newlines x ignore whitespace in regex o perform #{...} substitutions only once
正则表达式用法总结:
1. . 匹配除换行意外的任意字符
2. \w 匹配字母或数字或下划线或汉字
3. \s 匹配任意的空白字符
4. \d 匹配数字
5. \b 匹配单词的开始或结束
6. ^ 匹配字符串的开始
7. $ 匹配字符串的结束
8. * 重复零次或多次
9. + 重复一次或多次
10. ? 重复零次或一次
11. {n} 重复n次
12. {n,} 重复n次或更多
13. {n,m} 重复n次到m次
ip地址正则
$match = array();
$IP = "198.168.1.78";
preg_match('/^(([1-9]?[0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]).){3}([1-9]?[0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$/',$IP, $match);
var_dump($match);
邮箱正则
$match = array();
$email = "test@ansoncheung.tk";
preg_match('/^[^0-9][a-zA-Z0-9_]+([.][a-zA-Z0-9_]+)*[@][a-zA-Z0-9_]+([.][a-zA-Z0-9_]+)*[.][a-zA-Z]{2,4}$/',$email, $match);
var_dump($match);
用户名正则
$match = array();
$username = "user_name12";
#preg_match('/^[a-z\d_]{5,20}$/i', $username, $match);
preg_match('/^[a-z]+[a-z0-9_]+$/i', $username, $match);
var_dump($match);