Js正则学习笔记

众所周知正则表达式是十分强大的存在,编码时能够熟练使用正则能够极大的简化代码,因此掌握正则非常有必要。

创建正则语法:

// 创建正则的两种方式
//
1.构造函数  let reg = new RegExp('匹配模式', '修饰符[i/m/g]')
let reg = new RegExp('test', 'g');
// 2.字面量   let reg = /匹配模式/修饰符
let reg1 = /test/g;

正则修饰符:

// i  忽略大小写 
// m  多行匹配
// g  全局匹配

// 例1:
let str = 'testTEST';
let reg = /test/gi;   // 全局匹配 并 忽略大小写
str.match(reg);  // ["test", "TEST"] 

//例2:
str = 'test\n helloworld';
reg = /test$/g
str.match(reg)  // null
reg = /test$/gm
str.match(reg) // ["test"]

正则表达式方法:

test() 方法用于检测一个字符串是否匹配某个模式,返回true、false 
exec() 法用于检索字符串中的正则表达式的匹配, 返回数组
// 例1:
let str = 'this is test';
let reg = /test/;
reg.test(str);  // true
// 例2:
let str1 = 'this is test2';
let reg1 = /test/;
reg1.exec(str1);  // ["test",...]

可用于正则的字符串方法:

search()  检索与正则表达式相匹配的值,返回位置下标
match() 找到一个或多个匹配的字符串,返回匹配到的值
replace() 替换匹配的字符串,返回替换后的值
split() 将字符串分割为数组,返回数组
// 例1:
let str2 = 'this is searchTest';
let reg2 = /Test/i;
str2.search(reg2);  // 14
// 例2: 
let str3 = 'this is matchTESTMATch';
let reg3 = /match/gi;
str3.match(reg3);   //["match", "MATch"]
// 例3:
let str4 = 'this is replaceTest';
let reg4 = /replaceTEST/i;
str4.replace(reg4, '修改后的字符串');
// 例4:
let str5 = '/Date(1515554448781)';
let reg5 = /(\/Date\(|\))/g;
str5.replace(reg5, '');  // 1515554448781

// 例5:
let str6 = '/Date(1515554448781)';
let reg6 = /(\/Date\(|\))/g;
str6.split(reg6);   // ["", "/Date(", "1515554448781", ")", ""]

正则基础表达式:

[a-z]  a-z 任意字符
[test]  []中任意字符
[^dsad] 非[]中的任意字符
[abc|efg] []中任意字符
(abc|efg) () abc字符串或efg字符串

n*   0个或多个
n+  1个或多个
n{x} x个字符
n{x, } 大于等于x个字符
n{x, y} x到y个字符
n(?=x)  匹配任何其后紧接指定字符串 n 的字符串。
n(?!x)   匹配任何其后没有紧接指定字符串 n 的字符串。
^n 以n开头
n$ 以n结尾

 

posted @ 2019-05-29 17:54  有梦想的咸鱼-  阅读(203)  评论(0编辑  收藏  举报