概述
正则表达式 ( Regular Expression
,在代码中常简写为 regex
、 regexp
或 RE
),是一种文本模式,包括普通字符 ( 如 a
到 z
之间的字母 ) 和特殊字符 ( 元字符 ) ,是计算机科学的一个概念。正则表达式使用单个字符串来描述、匹配一系列匹配某个句法规则的字符串,通常被用来检索、替换那些符合某个模式(规则)的文本,如下整理了 常用正则表达式 。
语法
普通字符
普通字符包括没有显式指定为元字符的所有打印和不可打印字符,包括所有大小写字母、所有数字、所有标点符号和一些其他符号。
字符 | 描述 |
---|---|
[ABC] | 匹配 [...] 中的所有字符。 |
^[ABC] | 匹配除 [...] 中字符的所有字符。 |
[A-Z] | [A-Z] 表示一个区间,匹配所有大写字母,[a-z] 表示所有小写字母。 |
. | 匹配除换行符 ( \n 、\r ) 之外的任何单个字符,相当于 [^\n\r] 。 |
[\s\S] | 匹配所有,\s 匹配所有空白符,包括换行,\S 匹配非空白符,不包括换行。 |
\w | 匹配字母、数字、下划线,等价于 [A-Za-z0-9_] |
\d | 匹配任意一个阿拉伯数字( 0到9 ),等价于 [0-9] |
非打印字符
字符 | 描述 |
---|---|
\cx | |
\f | |
\n | |
\r | |
\s | |
\S | |
\t | |
\v |
特殊字符
字符 | 描述 |
---|---|
$ | |
() | |
* | |
+ | |
. | |
[ | |
? | |
\ | |
^ | |
{ | |
` | ` |
限定符
字符 | 描述 |
---|---|
* | |
+ | |
? | |
{n} | |
{n,} | |
{n,m} |
定位符
字符 | 描述 |
---|---|
^ | |
$ | |
\b | |
\B |
选择
反向引用
修饰符(标记)
修饰符 | 含义 | 描述 |
---|---|---|
i | ||
g | ||
m | ||
s |
元字符
运算符优先级
匹配规则
基本模式匹配
字符簇
确定重复出现
常用正则表达式
规则名称 | 正则表达式 |
---|---|
火车车次 | /^[GCDZTSPKXLY1-9]\d{1,4}$/ |
手机机身码(IMEI ) | /^\d{15,17}$/ |
社会统一信用代码 | /^[0-9A-HJ-NPQRTUWXY]{2}\d{6}[0-9A-HJ-NPQRTUWXY]{10}$/ |
HTML、XML 注释 | /^<!--[\s\S]*?-->$/ |
GUID / UUID | /^[a-f\d]{4}(?:[a-f\d]{4}-){4}[a-f\d]{12}$/i |
版本号(格式需为 X.Y.Z) | /^\d+(?:\.\d+){2}$/ |
金额(支持负数、千分位分隔符) | /^-?\d+(,\d{3})*(\.\d{1,2})?$/ |
银行卡号(10到30位) | /^[1-9]\d{9,29}$/ |
中文姓名 | /^(?:[\u4e00-\u9fa5·]{2,16})$/ |
英文姓名 | /(^[a-zA-Z][a-zA-Z\s]{0,20}[a-zA-Z]$)/ |
手机号(宽松) | |
座机电话(国内) | |
身份证号(二代身份证) | |
账号是否合法 | /^[a-zA-Z]\w{4,15}$/ |
中文 / 汉字 | /^[\u4E00-\u9FA5]+$/ |
小数 | /^\d+\.\d+$/ |
数字 | /^\d{1,}$/ |
数字和字母组成 | /^[A-Za-z0-9]+$/ |
不能包含字母 | /^[^A-Za-z]*$/ |
匹配连续重复字符 | /(.)\1+/ |