76 - 程序员常用正则表达式速查

适用人群:所有开发者
类型:速查手册

基础语法

符号说明示例
.任意字符a.c 匹配 abc, a1c
*0次或多次ab*c 匹配 ac, abc, abbc
+1次或多次ab+c 匹配 abc, abbc
?0次或1次ab?c 匹配 ac, abc
^开头^Hello
$结尾world$
\d数字\d{3} 匹配3位数字
\w字母数字下划线\w+
\s空白字符\s+
[]字符集[aeiou] 元音字母
[^]排除[^0-9] 非数字
{n}恰好n次\d{4} 4位数字
{n,m}n到m次\d{2,4} 2-4位数字
()捕获组(\d{4})-(\d{2})
|cat|dog
\b单词边界\bword\b

常用正则表达式

验证类

手机号(中国大陆):
^1[3-9]\d{9}$

邮箱:
^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$

身份证号(18位):
^[1-9]\d{5}(19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}[\dXx]$

URL:
https?:\/\/[^\s]+\.[^\s]+

IP地址(IPv4):
^((25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(25[0-5]|2[0-4]\d|[01]?\d\d?)$

中文字符:
^[\u4e00-\u9fa5]+$

用户名(字母开头,允许字母数字下划线,4-16位):
^[a-zA-Z][a-zA-Z0-9_]{3,15}$

密码强度(至少8位,含大小写字母和数字):
^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).{8,}$

日期格式(YYYY-MM-DD):
^\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01])$

邮政编码(中国):
^[1-9]\d{5}$

提取类

提取数字:
\d+\.?\d*

提取中文:
[\u4e00-\u9fa5]+

提取邮箱:
[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}

提取链接:
https?:\/\/[^\s"'<>]+

提取图片src:
<img[^>]+src=["']([^"']+)["']

提取HTML标签内容:
<(\w+)[^>]*>(.*?)<\/\1>

提取#标签#:
#([^#]+)#

提取@用户:
@([\w\u4e00-\u9fa5]+)

替换类

去除HTML标签:
<[^>]+>  →  (空)

去除多余空格:
\s+  →  (一个空格)

手机号脱敏:
(\d{3})\d{4}(\d{4})  →  $1****$2

邮箱脱敏:
(\w{1,3})[^@]*(@.*)  →  $1***$2

日期格式转换(MM/DD/YYYY → YYYY-MM-DD):n(\d{2})\/(\d{2})\/(\d{4})  →  $3-$1-$2


各语言使用示例

// JavaScript
const regex = /^1[3-9]\d{9}$/;
regex.test('13812345678');  // true
'Hello 13812345678'.match(/\d{11}/g);  // ['13812345678']
'hello world'.replace(/world/, 'JS');  // 'hello JS'

# Python
import re
regex = r'^1[3-9]\d{9}$'
re.match(regex, '13812345678')  # Match
re.findall(r'\d+', 'a1b22c333')  # ['1', '22', '333']
re.sub(r'\s+', ' ', 'hello   world')  # 'hello world'

// PHP
preg_match('/^1[3-9]\d{9}$/', '13812345678');  // 1
preg_match_all('/\d+/', 'a1b22c333', $matches);
preg_replace('/\s+/', ' ', 'hello   world');

// Go
import "regexp"
re := regexp.MustCompile(`^1[3-9]\d{9}$`)
re.MatchString("13812345678")  // true
re.FindAllString("a1b22c333", -1)  // [1 22 333]


调试工具

工具链接
regex101.com最好的在线正则调试工具
regexr.com可视化正则表达式
debuggex.com正则图解
返回首页