用途:exec()更适用于在循环中逐个检索匹配项,特别是当需要访问正则表达式的lastIndex属性时。而match()则更直接地返回所有匹配项,适合一次性获取所有匹配结果。 示例 let str = "The rain in SPAIN stays mainly in the plain"; let regex= /ain/g;//使用 exec()let execResult;while((execResult = regex....
while (match = regex.exec(string)) { matches.push(match) } console.log(matches) // [ // ["test1", "e", "st1", "1", index: 0, input: "test1test2test3", groups: undefined], // ["test2", "e", "st2", "2", index: 5, input: "test1test2test3", groups: undefined], //...
const str = 'aBc AbBc aBBBBc';const result = str.match(regex);console.log(result); // 输出: [ 'aBc', index: 0, input: 'aBc AbBc aBBBBc', groups: undefined ] 在这个例子中,由于我们设置了“i”标志,所以正则表达式在匹配时忽略了大小写。因此,它能够匹配到“aBc”。 请注意,当使用构造函...
log(str.match(reg1)); //[ 'hello', index: 0, input: 'hello world hello', groups: undefined ] console.log(str.match(reg2));//[ 'hello', 'hello' ] 3. split 切割字符串 代码语言:javascript 代码运行次数:0 运行 AI代码解释 var str = 'add123sum456zhangsan789lisi' var reg = ...
match(/h(e)(?:ll)(o)/); // ["hello", "e", "o", index: 0, input: "hello world", groups: undefined] 这样就是只要两个子项了,分别为:"e"、"o"。具备子项功能的方法还有:exec、matchAll、replace,这里就不一一演示了。 具名组匹配 可以发现子项的排列是根据顺序来决定的,除了顺序外,还...
JavaScript中String的match方法详解 String.prototype.match() ** String.prototype.match()方法返回通过一个正则表达式匹配到的字符串结果。** varparagraph='The quick brown fox jumps over the lazy dog. It barked.'; varregex=/[A-Z]/g; varfound=paragraph.match(regex);...
在JavaScript 中常用正则匹配方法有match和exec, 这两个方法属于不同的对象方法。 match是字符串方法,写法为:str.match(regex) exec是正则表达式方法,写法为:regex.exec(str) 两者在匹配成功时返回的都是数组,在没有匹配上时返回的都是 null,在一些情况下两者返回的结果相同,故在没有深入了解两者的使用规则前,会...
// 无全局修饰符的情况const regex = /ab{2,4}c/const string = 'abc abbc abbbc abbbbc abbbbbc'console.log(string.match(regex))// ["abbc", index: 4, input: "abc abbc abbbc abbbbc abbbbbc", groups: undefined]纵向模糊匹配 纵向模糊指的是,一个正则匹配的字符串,具体到某一位字符时...
groups:一个命名捕获组的对象,其键是名称,值为捕获组,如果未定义命名捕获组,则为 undefined。 带有标记 g 的实例代码: conststrText ="Hello China";constregex =/[A-Z]/g;// 大写字母正则表达式console.log(strText.match(regex));// [ 'H', 'C' ] ...
log(match.groups.month) // → 03 console.log(match.groups.day) // → 04 这也是为什么在使用 capture groups 的时候输出里老是有一个 groups === undefined解构小技巧 值得注意的是, named group 其实也是 capture group, 只不过是特殊的 capture group, 所以下面的代码依然可以运行...