Javascript常用正则表达式的示例分析

发布时间:2021-08-18 15:09:15 作者:小新
来源:亿速云 阅读:103

小编给大家分享一下Javascript常用正则表达式的示例分析,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获,下面让我们一起去了解一下吧!

模式修饰符的可选参数

两个测试方法

test

const test = new RegExp('hello world', 'ig');
console.log(test.test('hello world')); // true

exec

返回的是数组,有就返回数组的值,没有返回为null

const test = new RegExp('hello world', 'ig');
console.log(test.exec('hello')); // null

四个正则表达式方法

match(pattern)

将所有匹配的字符串组合成数组返回

const pattern=/Box/ig;
const str="This is a Box! The is a box!";
console.log(str.match(pattern));

search(pattern)

返回字符串中pattern开始位置,忽略全局匹配

const pattern=/Box/i;	//
const str="This is a Box! The is a box!";
console.log(str.search(pattern)); // 10

replace(pattern)

替换匹配到的字符串

const pattern=/Box/ig;
const str="This is a Box! The is a box!";
console.log(str.replace(pattern,'Tom'));

split(pattern)

返回字符串指定pattern拆分数组

const pattern = / /ig;	//空格
const str = "This is a Box! The is a box!";
console.log(str.split(pattern)); //以空格进行分割,返回的是数组
// 输出结果
// [ 'This', 'is', 'a', 'Box!', 'The', 'is', 'a', 'box!' ]

匹配模式

\w表示a-zA-Z_
锚元字符匹配(^ $) ^强制收匹配 $强制尾匹配,并且只匹配一个

const pattern=/^[a-z]oogle\d$/;
const str="aoogle2";
console.log(pattern.test(str)); // true

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

|表示匹配或选择模式

const pattern=/baidu|google|bing/; //匹配或选择其中某个字符,不是相等,包含的意思
const str = "baidu a google"; 
console.log(pattern.test(str)); //返回true

常用正则表达式

检查邮政编码

const pattern = /^[1-9]{1}[0-9]{5}$/;
const str = "122534"; //共6位数,第一位不能为0
console.log(pattern.test(str)); // true

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

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

删除多余空格

方法一: 使用replace只匹配一个,所以使用+匹配多个

 var pattern=/^\s+/; 
 var str=" google ";
 var result=str.replace(pattern,'');
 pattern=/\s+$/;
 result=result.replace(pattern,'');

方法二: (.+)贪婪模式,使用惰性模式,后面的空格不让匹配

var pattern=/^\s+(.+?)\s+$/;
 var str=" google ";
 var result=pattern.exec(str,'')[1];

 console.log('|'+result+'|');

方法三: (.+)贪婪模式,改为惰性模式,使用分组模式,只取匹配的内容

var pattern=/^\s+(.+?)\s+$/;
 var str=" google ";
 var result=str.replace(pattern,'$1'); //使用分组模式

 console.log('|'+result+'|'); // |google|

简单邮箱验证

var pattern=/^([\w\.\_]+)@([\w\_]+)\.([a-zA-Z]){2,4}$/;
var str="qzfweb@gmail.com";
console.log(pattern.test(str)); // true

以上是“Javascript常用正则表达式的示例分析”这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注亿速云行业资讯频道!

推荐阅读:
  1. 【专题】常用JavaScript正则表达式(regexp)汇编与示例
  2. JavaScript的示例分析

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

javascript

上一篇:JS中如何使用serialize()

下一篇:Angular8如何实现表单及其验证

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》