match()
方法将 字符串 与 正则表达式 匹配的结果返回。
示例
const message = "JavaScript is a fun programming language.";
// regular expression that checks if message contains 'programming'
const exp = /programming/;
// check if exp is present in message
let result = message.match(exp);
console.log(result);
/*
Output: [
'programming',
index: 20,
input: 'JavaScript is a fun programming language.',
groups: undefined
]
*/
match() 语法
match()
方法的语法是:
str.match(regexp)
其中,str 是一个字符串。
match() 参数
match()
方法接收:
- regexp - 一个正则表达式对象(如果非 RegExp 对象,则会自动转换为
RegExp
)
注意: 如果不提供任何参数,match()
将返回 [""]
。
match() 返回值
- 返回一个包含匹配项的 数组,每个匹配项占一个元素。
- 如果未找到匹配项,则返回
null
。
示例 1:使用 match()
const string = "I am learning JavaScript not Java.";
const re = /Java/;
let result = string.match(re);
console.log("Result of matching /Java/ :");
console.log(result);
const re1 = /Java/g;
let result1 = string.match(re1);
console.log("Result of matching /Java/ with g flag:")
console.log(result1);
输出
Result of matching /Java/ : [ 'Java', index: 14, input: 'I am learning JavaScript not Java.', groups: undefined ] Result of matching /Java/ with g flag: [ 'Java', 'Java' ]
在这里,我们可以看到,如果不使用 g
标志,我们只得到第一个匹配项作为结果,但包含索引、输入和分组等详细信息。
注意:如果正则表达式不包含 g
标志,str.match()
将仅返回第一个匹配项,类似于 RegExp.exec()
。返回的项还将具有以下附加属性:
groups
- 一个命名捕获组的对象,键为名称,值为捕获的匹配项。index
- 搜索结果的索引。input
- 搜索字符串的副本。
示例 2:匹配字符串中的部分
const string = "My name is Albert. YOUR NAME is Soyuj.";
// expression matches case-insensitive "name is"+ any alphabets till period (.)
const re = /name\sis\s[a-zA-Z]+\./gi;
let result = string.match(re);
console.log(result); // [ 'name is Albert.', 'NAME is Soyuj.' ]
// using named capturing groups
const re1 = /name\sis\s(?<name>[a-zA-Z]+)\./i;
let found = string.match(re1);
console.log(found.groups); // {name: "Albert"}
输出
[ 'name is Albert.', 'NAME is Soyuj.' ] {name: "Albert"}
这里,我们使用正则表达式来匹配字符串的特定部分。如上所示的语法,我们也可以在匹配中使用捕获组。
另请阅读