正则表达式

1. 预定义类

.   [^\n\r] 除了换行和回车之外的任意字符(“”不行)
\d  [0-9]       数字字符
\D  [^0-9]     非数字字符

\s  [ \t\n\x0B\f\r]  空白字符 
\S  [^ \t\n\x0B\f\r]     非空白字符

\w  [a-zA-Z_0-9]         单词字符
\W  [^a-zA-Z_0-9]       非单词字符

2. 简单类

1. /string/.test(“string”);            // 必须是完整的,只多不能少
   /andy/.test(“andy”)                  // true
   /andy/.test(“andylv”)                // true
   /andy/.test(“an”)                    // false
   
2.  /[string]/.test(“string”);        // 只要包含里面的任何一个就可以
    /[andy]/.test("andy");            // true
    /[andy]/.test("an");                    // true
    /[andy]/.test("ady");               // true
    /[andy]/.test("anll");              // true
    /[andy]/.test("assd");              // true
    /[andy]/.test("ss");                    // false
    /[3aH8]/.test("ss");                    // false

3. 负向类

中括号内,前面加个元字符^进行取反,不是括号里面的字符(一部分也不行)。
(可以不够,但是不能多)(不够和正好,返回false;多了或者没有返回true)
 console.log(/[^abc]/.test('a'));  // false
 console.log(/[^abc]/.test('gg')); // true
 console.log(/[^abc]/.test('aggbc')); // true
注意:  这个符号 ^  一定是写到方括号里面

4. 范围类

有时匹配的东西过多,而且类型又相同,全部输入太麻烦,我们可以在中间加了个横线
console.log(/[a-z]/.test('1111')); // false
console.log(/[A-Z]/.test('aa')); // false

5. 组合类

用中括号匹配不同类型的单个字符。
console.log(/[a-m1-5]/.test("b"))//true

6. 量词 (多个字母,重复最后一个)

*   (贪婪)   重复零次或更多   (>=0)
+   (懒惰)   重复一次或更多次  (>=1)
?   (占有)   重复零次或一次   (0||1)  要么有 要么没有
{}  重复多少次的意思   可以有多少个  
您的银行卡密码只能是 6位      {6}
{n} n次  (x=n)  
{n,}    重复n次或更多  (x>=n)
{n,m} 重复出现的次数比n多但比m少 (n<=x<=m)
*  相当于   {0,}
+  相当于    {1,}
?  相当于   {0,1}
x | y  x 或者 y
() 提啊高权限,有限计算

// 封装自己的trim方法
function trim() {
    return str.replace(/(^\s+)|(\s+$)/g,""); // 去掉前面和后面的空格
}

7. 常用的正则表达式

qq号: /^[1-9][0-9]{4,}$/
手机号: /^((13[0-9])|(15[^4,\D])|(18[0-9]))\d{8}$/
邮箱: /^[\w\-\.]{5,}\@[\w]+\.[\w]{2,4}$/
座机: /(^0\d{2}-8\d{7}$)|(^0\d{3}-3\d{6}$)/
用户名: /[\u4e00-\u9fa5]{2,8}/
密码:
    /^[a-zA-Z0-9_\-$]{6,18}$/  
    /^[A-Za-z0-9]+[_$][A-Za-z0-9]*$/ // 数字加大小字母加下划线或者$符
    /^([a-z].*[0-9])|([A-Z].*[0-9])|[0-9].*[a-zA-Z]$/  // 数字加字母
    /^([a-z].*[A-Z])|([A-Z].*[a-z])$/  //区分大小写字母
    
    
    // 注意:
    /^([a-z].*[A-Z])$/  //表示只要前面是小写字母和最后面是大写就行,且中间不管小写还是大写都无所谓
    // 在这里, . 表示任意字符不包括"",后面接*,表示任意字符0个或多个
    如: /^([a-z].*[A-Z])$/.test('aaEEAAAc') // false
    如: /^([a-z].*[A-Z])$/.test('aaEEAAA') // true
    如: /^([a-z].*[A-Z])$/.test('aA') // true

你可能感兴趣的:(正则表达式)