String.prototype.match()
是 JavaScript 中的一个方法,用于在字符串中搜索匹配正则表达式的子串,并返回一个数组,其中包含了整个匹配结果以及任何括号捕获的子匹配。如果没有找到匹配项,则返回 null
。
()
在正则表达式中创建,可以捕获匹配的子串,并将其作为数组元素返回。g
标志进行全局搜索,返回所有匹配项。i
标志进行不区分大小写的搜索。m
标志进行多行搜索。// 基本用法
let str = "Hello, my email is example@example.com and my phone is 123-456-7890.";
let emailMatch = str.match(/[\w.-]+@[\w.-]+/);
console.log(emailMatch); // 输出: ["example@example.com"]
// 使用全局标志
let phoneNumbers = str.match(/\d{3}-\d{3}-\d{4}/g);
console.log(phoneNumbers); // 输出: ["123-456-7890"]
// 使用捕获组
let matchWithGroups = str.match(/(\d{3})-(\d{3})-(\d{4})/);
console.log(matchWithGroups); // 输出: ["123-456-7890", "123", "456", "7890"]
问题:match()
方法返回 null
,即使看起来应该有匹配项。
原因:
g
,导致只返回第一个匹配项。解决方法:
console.log()
打印字符串和正则表达式进行调试。g
。let str = "The quick brown fox jumps over the lazy dog";
let matches = str.match(/the/gi); // 注意 'g' 和 'i' 标志
console.log(matches); // 输出: ["The", "the"]
通过以上方法,可以有效地使用 match()
方法进行字符串匹配和处理。
领取专属 10元无门槛券
手把手带您无忧上云