String.prototype.match()

String 值的 match() 方法检索该字符串与 正则表达式 的匹配结果。

¥The match() method of String values retrieves the result of matching this string against a regular expression.

Try it

语法

¥Syntax

js
match(regexp)

参数

¥Parameters

regexp

正则表达式对象,或任何具有 Symbol.match 方法的对象。

如果 regexp 不是 RegExp 对象并且没有 Symbol.match 方法,则使用 new RegExp(regexp) 将其隐式转换为 RegExp

如果不给出任何参数,直接使用 match() 方法,你会得到一个空字符串的 Array[""],因为这相当于 match(/(?:)/)

返回值

¥Return value

Array,其内容取决于全局 (g) 标志是否存在,或者 null(如果未找到匹配项)。

¥An Array whose contents depend on the presence or absence of the global (g) flag, or null if no matches are found.

  • 如果使用 g 标志,则将返回与完整正则表达式匹配的所有结果,但不包括捕获组。
  • 如果未使用 g 标志,则仅返回第一个完整匹配项及其相关捕获组。在这种情况下,match() 将返回与 RegExp.prototype.exec() 相同的结果(具有一些额外属性的数组)。

描述

¥Description

String.prototype.match 本身的实现非常简单 - 它只是调用参数的 Symbol.match 方法,并将字符串作为第一个参数。实际实现来自 RegExp.prototype[Symbol.match]()

¥The implementation of String.prototype.match itself is very simple — it simply calls the Symbol.match method of the argument with the string as the first parameter. The actual implementation comes from RegExp.prototype[Symbol.match]().

有关传递正则表达式时 match() 语义的更多信息,请参阅 RegExp.prototype[Symbol.match]()

¥For more information about the semantics of match() when a regex is passed, see RegExp.prototype[Symbol.match]().

示例

¥Examples

使用 match()

¥Using match()

在以下示例中,match() 用于查找 "Chapter" 后跟一个或多个数字字符,后跟小数点和数字字符零次或多次。

¥In the following example, match() is used to find "Chapter" followed by one or more numeric characters followed by a decimal point and numeric character zero or more times.

正则表达式包含 i 标志,因此将忽略大小写差异。

¥The regular expression includes the i flag so that upper/lower case differences will be ignored.

js
const str = "For more information, see Chapter 3.4.5.1";
const re = /see (chapter \d+(\.\d)*)/i;
const found = str.match(re);

console.log(found);
// [
//   'see Chapter 3.4.5.1',
//   'Chapter 3.4.5.1',
//   '.1',
//   index: 22,
//   input: 'For more information, see Chapter 3.4.5.1',
//   groups: undefined
// ]

在上面的比赛结果中,'see Chapter 3.4.5.1' 是整场比赛。'Chapter 3.4.5.1'(chapter \d+(\.\d)*) 俘获。'.1'(\.\d) 捕获的最后一个值。index 属性 (22) 是整个匹配的从零开始的索引。input 属性是解析的原始字符串。

¥In the match result above, 'see Chapter 3.4.5.1' is the whole match. 'Chapter 3.4.5.1' was captured by (chapter \d+(\.\d)*). '.1' was the last value captured by (\.\d). The index property (22) is the zero-based index of the whole match. The input property is the original string that was parsed.

将全局和 ignoreCase 标志与 match()一起使用

¥Using global and ignoreCase flags with match()

以下示例演示了全局标志和忽略大小写标志与 match() 的使用。返回所有字母 AE 以及 ae,每个字母在数组中都有自己的元素。

¥The following example demonstrates the use of the global flag and ignore-case flag with match(). All letters A through E and a through e are returned, each its own element in the array.

js
const str = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
const regexp = /[A-E]/gi;
const matches = str.match(regexp);

console.log(matches);
// ['A', 'B', 'C', 'D', 'E', 'a', 'b', 'c', 'd', 'e']

注意:另请参见 String.prototype.matchAll()使用标志进行高级搜索

¥Note: See also String.prototype.matchAll() and Advanced searching with flags.

使用命名捕获组

¥Using named capturing groups

在支持命名捕获组的浏览器中,以下代码将 "fox""cat" 捕获到名为 animal 的组中:

¥In browsers which support named capturing groups, the following code captures "fox" or "cat" into a group named animal:

js
const paragraph = "The quick brown fox jumps over the lazy dog. It barked.";

const capturingRegex = /(?<animal>fox|cat) jumps over/;
const found = paragraph.match(capturingRegex);
console.log(found.groups); // {animal: "fox"}

使用不带参数的 match()

¥Using match() with no parameter

js
const str = "Nothing will come of nothing.";

str.match(); // returns [""]

使用 match() 和非 RegExp 实现 [Symbol.match]()

¥Using match() with a non-RegExp implementing [Symbol.match]()

如果一个对象有 Symbol.match 方法,它可以用作自定义匹配器。Symbol.match 的返回值成为 match() 的返回值。

¥If an object has a Symbol.match method, it can be used as a custom matcher. The return value of Symbol.match becomes the return value of match().

js
const str = "Hmm, this is interesting.";

str.match({
  [Symbol.match](str) {
    return ["Yes, it's interesting."];
  },
}); // returns ["Yes, it's interesting."]

非 RegExp 作为参数

¥A non-RegExp as the parameter

regexp 参数是字符串或数字时,使用 new RegExp(regexp) 将其隐式转换为 RegExp

¥When the regexp parameter is a string or a number, it is implicitly converted to a RegExp by using new RegExp(regexp).

js
const str1 =
  "NaN means not a number. Infinity contains -Infinity and +Infinity in JavaScript.";
const str2 =
  "My grandfather is 65 years old and My grandmother is 63 years old.";
const str3 = "The contract was declared null and void.";
str1.match("number"); // "number" is a string. returns ["number"]
str1.match(NaN); // the type of NaN is the number. returns ["NaN"]
str1.match(Infinity); // the type of Infinity is the number. returns ["Infinity"]
str1.match(+Infinity); // returns ["Infinity"]
str1.match(-Infinity); // returns ["-Infinity"]
str2.match(65); // returns ["65"]
str2.match(+65); // A number with a positive sign. returns ["65"]
str3.match(null); // returns ["null"]

如果特殊字符未正确转义,这可能会产生意外结果。

¥This may have unexpected results if special characters are not properly escaped.

js
console.log("123".match("1.3")); // [ "123" ]

这是匹配,因为正则表达式中的 . 匹配任何字符。为了使其仅匹配特定的点字符,你需要对输入进行转义。

¥This is a match because . in a regex matches any character. In order to make it only match specifically a dot character, you need to escape the input.

js
console.log("123".match("1\\.3")); // null

规范

Specification
ECMAScript Language Specification
# sec-string.prototype.match

¥Specifications

浏览器兼容性

BCD tables only load in the browser

¥Browser compatibility

也可以看看