//示例1:
var str = “aaabbbcccaaabbbccc”;
var res = str.match(/aaa/); //没有使用g选项
console.log(res); //输出[ ‘aaa‘, index: 0, input: ‘aaabbbcccaaabbbccc‘ ] 第一个表示匹配的字符串;第二个表示匹配的字符串坐在的索引位置,从0开始计算;第三个表示原始字符串;
//示例2:
var str = “aaabbbcccaaabbbccc”;
var res = str.match(/aaa/g); //使用g选项,全局匹配
console.log(res); //输出[ ‘aaa‘, ‘aaa‘ ] 所有匹配的字符串组成的数组
//示例3:
var total_str = "L00002Ab.cd"
var need_data = total_str.match("L(.*?)Ab.cd")
console.log(need_data)
打印结果为:
[ ‘L00002Ab.cd‘,
‘00002‘,
index: 0,
input: ‘L00002Ab.cd‘,
groups: undefined ]
所以想要获取自己的想要的结果,就是need_data[1]
//示例1:
var str = “aaabbbcccaaabbbccc”;
var regExp = /aaa/; //未使用g选项
var res = regExp .exec(str);
console.log(res); //输出[ ‘aaa‘, index: 0, input: ‘aaabbbcccaaabbbccc‘ ]
//示例2:
var str = “aaabbbcccaaabbbccc”;
var regExp = /aaa/g; //使用g选项
var res = regExp .exec(str);
console.log(res); //输出[ ‘aaa‘, index: 0, input: ‘aaabbbcccaaabbbccc‘ ]
//示例3:
var str = “aaabbbccc1234aaabbbccc”;
var regExp = /ccc([0-9]+)aaa/;
var res = regExp .exec(str);
console.log(res); //输出[ ‘ccc1234aaa‘, ‘1234‘, index: 6, input: ‘aaabbbccc1234aaabbbccc‘ ] 第一个表示整个正则表达式所匹配的内容;第二个表示()内容的子表达式所匹配的内容;第三个和第四个同上
//示例4:
var str = “aaabbbccc1234aaabbbcccaaabbbccc5678aaabbbccc”;
var reg = /ccc([0-9]+)aaa/;
var res = reg.exec(str);
console.log(res); //输出同示例三,因为exec只返回第一个匹配的字符串,如果想全部返回,则需要借助while循环和g参数来实现,如下
var str = “aaabbbccc1234aaabbbcccaaabbbccc5678aaabbbccc”;
var reg = /ccc([0-9]+)aaa/g;
while(res = reg.exec(str)){
console.log(res);
}
//输出如下:
[ ‘ccc1234aaa‘, ‘1234‘, index: 6, input: ‘aaabbbccc1234aaabbbcccaaabbbccc5678aaabbbccc‘ ][ ‘ccc5678aaa‘, ‘5678‘, index: 28, input: ‘aaabbbccc1234aaabbbcccaaabbbccc5678aaabbbccc‘ ]
//使用这个方法时切记加上g选项,否则while循环将无法跳出,每次都循环第一个匹配项,导致死循环,可能卡死!
//示例1:
var str = “aaabbbcccaaabbbccc”;
var reg = /[a-z]+/;
var res = reg.test(str);
console.log(res); //输出true
//示例2:
var str = “aaabbbcccaaabbbccc”;
var reg = /[0-9]+/;
var res = reg.test(str);
console.log(res); //输出false
//该函数一般用来检测某字符串是否符合指定的规则
//示例1:
var str = “aaabbbcccaaabbbccc”;
var reg = /ccc/;
var res = str.search(reg);
console.log(res); //输出 6
//示例1:
var str = “aaabbbcccaaabbbccc”;
var reg = /aaa/;
var res = str.replace(reg, ’111′);
console.log(res);//返回111bbbcccaaabbbccc ,只替换第一个匹配项,若需要替换所有则需要使用g选项
//示例1:
var str = “aaa,bbb,ccc”;
var reg = /,/;
var res = str.split(reg);
console.log(res); //输出[ ‘aaa‘, ‘bbb‘, ‘ccc‘ ]
//其实这里可以简单的写为var res = str.split(“,”);
//示例2:
var str = “aaa,bbb:ccc@ddd#eee”;
var reg = /[,:@#]/;
var res = str.split(reg);
console.log(res); //输出[ ‘aaa‘, ‘bbb‘, ‘ccc‘, ‘ddd‘, ‘eee‘ ] 这才是用正则的强大之处
//示例3.
var str = “aaa,bbb:ccc@ddd#eee”;
var reg = /[,:@#]/;
var res = str.split(reg, 3);
console.log(res); //输出[ ‘aaa‘, ‘bbb‘, ‘ccc‘]
Nodejs正则表达式函数之match、test、exec、search、split、replace使用详解
原文:https://www.cnblogs.com/haiguixiansheng/p/10749942.html