RegExp对象
创建一个RegExp对象:
var patt=new RegExp(pattern,modifiers);
或更简单的方法
var patt=/pattern/modifiers;
- pattern表示你要匹配的内容,
- modifiers表示你匹配的范围及方式
modifiers的取值:(可以两个都选择)
- i:模糊匹配(不区分大小写);
- g:全局匹配
正则表达式方法
-
test()
test() 方法是一个正则表达式方法。
test() 方法用于检测一个字符串是否匹配某个模式,如果字符串中含有匹配的文本,则返回 true,否则返回 false。
例子:
let reg=new RegExp('e','')
console.log(reg.test('abcdefg')); //true
console.log(reg.test('abcd')); //false
- exec()
exec() 方法是一个正则表达式方法。
exec() 方法用于检索字符串中的正则表达式的匹配。
该函数返回一个数组,其中存放匹配的结果。如果未找到匹配,返回值为 null。
数组中的内容:
[
pattern,
index:当前匹配项的位置,
input:匹配的字符串,
groups:undefined
]
例子:
let reg=new RegExp('e','')
console.log(reg.exec("Th ebst things in life are fre!"));
console.log(reg.exec("Th ebst things in life are fre!"))
//输出结果
[
'e',
index: 3,
input: 'Th ebst things in life are fre!',
groups: undefined
]
[
'e',
index: 3,
input: 'Th ebst things in life are fre!',
groups: undefined
]
注意加上全局匹配g之后,会有不一样的变化:
let reg=new RegExp('e','g')
console.log(reg.exec("Th ebst things in life are fre!"));
console.log(reg.exec("Th ebst things in life are fre!"));
console.log(reg.exec("Th ebst things in life are fre!"));
[
'e',
index: 3,
input: 'Th ebst things in life are fre!',
groups: undefined
]
[
'e',
index: 21,
input: 'Th ebst things in life are fre!',
PS C:\Users\fxk\Desktop\react学习\1.基础学习> node .\23.正则表达式.js
[
'e',
index: 3,
input: 'Th ebst things in life are fre!',
groups: undefined
]
[
'e',
index: 21,
input: 'Th ebst things in life are fre!',
groups: undefined
]
[
'e',
index: 25,
input: 'Th ebst things in life are fre!',
groups: undefined
]
可以看出,当设置为全局匹配之后,就会去后来的内容中匹配。