JS正则表达式基本用法与常用示例

正则 [正则] 模式修饰符的可选参数 [正则] 两个测试方法test、exec [正则] 4个正则表达式方法 [正则] 匹配模式 [正则] 常用正则表达式模式修饰符的可选参数:i: 忽略大小写 g: 全局匹配 m: 多行匹配 /hello/: 两个反斜杠是正则表达式的字面量表示法两个测试方法:test
  1. const test = new RegExp('hello world', 'ig');
  2. console.log(test.test('hello world')); // true
复制代码
exec 返回的是数组,有就返回数组的值,没有返回为null
  1. const test = new RegExp('hello world', 'ig');
  2. console.log(test.exec('hello')); // null
复制代码
4个正则表达式方法match(pattern) 将所有匹配的字符串组合成数组返回
  1. const pattern=/Box/ig;
  2. const str="This is a Box! The is a box!";
  3. console.log(str.match(pattern));
复制代码
search(pattern) 返回字符串中pattern开始位置,忽略全局匹配
  1. const pattern=/Box/i; //
  2. const str="This is a Box! The is a box!";
  3. console.log(str.search(pattern)); // 10
复制代码
replace(pattern) 替换匹配到的字符串
  1. const pattern=/Box/ig;
  2. const str="This is a Box! The is a box!";
  3. console.log(str.replace(pattern,'Tom'));
复制代码
split(pattern) 返回字符串指定pattern拆分数组
  1. const pattern = / /ig; //空格
  2. const str = "This is a Box! The is a box!";
  3. console.log(str.split(pattern)); //以空格进行分割,返回的是数组
  4. // 输出结果
  5. // [ 'This', 'is', 'a', 'Box!', 'The', 'is', 'a', 'box!' ]
复制代码
匹配模式

\w表示a-zA-Z_

锚元字符匹配(^ $) ^强制收匹配 $强制尾匹配,并且只匹配一个
  1. const pattern=/^[a-z]oogle\d$/;
  2. const str="aoogle2";
  3. console.log(pattern.test(str)); // true
复制代码

注意: ^符号在[]里面表示 非 在外边表示强制首匹配,并且只匹配一个 要想匹配多个值,使用+

\b表示到达边界

|表示匹配或选择模式
  1. const pattern=/baidu|google|bing/; //匹配或选择其中某个字符,不是相等,包含的意思
  2. const str = "baidu a google";
  3. console.log(pattern.test(str)); //返回true
复制代码
常用正则表达式检查邮政编码
  1. const pattern = /^[1-9]小贝[0-9]{5}$/;
  2. const str = "122534"; //共6位数,第一位不能为0
  3. console.log(pattern.test(str)); // true
复制代码
压缩包后缀名

\w等于a-zA-Z0-9_ 使用^限定从首字母匹配 .是特殊符号需要\n进行转义
|选择符必须使用()进行分组

  1. const pattern = /^[\w]+\.(zip|gz|rar)$/;
  2. const str="a12_.zip"; //文件名 字母_数字.zip,gz,rar
  3. console.log(pattern.test(str)); // true
复制代码

删除多余空格

方法一: 使用replace只匹配一个,所以使用+匹配多个
  1. var pattern=/^\s+/;
  2. var str=" google ";
  3. var result=str.replace(pattern,'');
  4. pattern=/\s+$/;
  5. result=result.replace(pattern,'');
  6. console.log('|'+result+'|'); // |google|
复制代码
方法二: (.+)贪婪模式,使用惰性模式,后面的空格不让匹配
  1. var pattern=/^\s+(.+?)\s+$/;
  2. var str=" google ";
  3. var result=pattern.exec(str,'')[1];
  4. console.log('|'+result+'|');
复制代码
方法三: (.+)贪婪模式,改为惰性模式,使用分组模式,只取匹配的内容
  1. var pattern=/^\s+(.+?)\s+$/;
  2. var str=" google ";
  3. var result=str.replace(pattern,'$1'); //使用分组模式
  4. console.log('|'+result+'|'); // |google|
复制代码
简单邮箱验证
  1. var pattern=/^([\w\.\_]+)@([\w\_]+)\.([a-zA-Z]){2,4}$/;
  2. var str="qzfweb@gmail.com";
  3. console.log(pattern.test(str)); // true
复制代码
github地址 JS正则表达式基本用法与常用示例
更多web视频、资料  http://www.makeru.com.cn/     web学习交流群:362513833
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值