JavaScript正则表达式-字符类
字符列表
在方括号内指定一个或者多个字符组成的字符列表,与字符列表中任意字符匹配,都被认为是匹配的。每次匹配只能匹配列表中的一个字符。
str = "bird,head,fed,meadow,3d";
reg_pattern = /[rea3s]d/g;
arr_m = str.match(reg_pattern);//arr_m = ["rd","ad","ed","ad","3d"]
str = "bird,head,*d,meadow,3d";
reg_pattern = /[\*ea]d/g;
arr_m = str.match(reg_pattern);//arr_m = ["ad","*d","ad"]
反向列表
匹配列表中指定字符以外的所有字符
反向列表通过在列表前加"^"符号进行定义
str = "bird,head,*d,meadow,3d";
reg_pattern = /[^fa3]d/g;
arr_m = str.match(reg_pattern);//arr_m = ["rd","*d"]
字符范围
用"-"符号将起始字符与结束字符连接起来,表示起始字符与结束字符之间所有字符。
str = "Great hope make great man!";
reg_pattern = /[a-z]a/g;
arr_m = str.match(reg_pattern);//arr_m = ["ea","ma","ea","ma"]
反向范围
在字符范围前加上"^"符号,表示匹配该字符范围以外任意字符
组合类
多种字符可以混合使用
str = "Hi!bit this biscuit";
reg_pattern = /[E-Kj-ms-zb0-9]i/g;
arr_m = str.match(reg_pattern);//arr_m = ["Hi","bi","bi","ui"]
预定义类
字符类 |
含义 |
. |
匹配除换行符\n和回车符之外的任何单个字符,等效于[^\n\r] |
\d |
匹配一个数字字符,等效于[0-9] |
\D |
与\d互补 |
\w |
匹配包括下划线的任何单个字符,包括A~Z,a~z,0~9和下划线"_",等效于[a-zA-Z0-9_] |
\W |
与\w互补 |
\s |
匹配任何Unicode空白字符,包括空格、制表符、换页符等,等效于[\f\t\n\r] |
\S |
与\S互补 |
[\b] |
退格字符Backspace |