DEV Community

Cover image for HarmonyOS Development: match and matchAll in Regularization
程序员一鸣
程序员一鸣

Posted on

HarmonyOS Development: match and matchAll in Regularization

Foreword

this article is based on Api13

regarding regular expressions, I have actually written related articles before, but I have not made a detailed analysis of match and matchAll. Although they are all used for common string matching, they still have certain differences in usage. Remember, regular expressions are applicable to all programming languages. There may be some differences in syntax and usage, but the basic principle is the same.

Let's look at the Source Code First:

match: matches a string to a regular expression and returns an array containing the search results.

 /**
     * Matches a string with a regular expression, and returns an array containing the results of that search.
     * @param regexp A variable name or string literal containing the regular expression pattern and flags.
     */
    match(regexp: string | RegExp): RegExpMatchArray | null;
Enter fullscreen mode Exit fullscreen mode

matchAll: matches a string to a regular expression and returns an iterable object of the match

get search results.

 /**
     * Matches a string with a regular expression, and returns an iterable of matches
     * containing the results of that search.
     * @param regexp A variable name or string literal containing the regular expression pattern and flags.
     */
    matchAll(regexp: RegExp): IterableIterator<RegExpMatchArray>;
Enter fullscreen mode Exit fullscreen mode

We can also see from the source code that the parameters and return values of the two are also different. In development, if it is a string, you can directly call these two methods.

Related introduction

the match method

first of all, match, it is a method of string object, used to find the content matching the regular expression in the string, can receive two types of parameters, one is string, the other is a RegExp object.

Where string is the string to be matched ,RegExp is a regular expression object or string, one thing to note if RegExp is not a regular expression object, it is implicitly converted to a regular expression object.

The return value of the match method depends on whether the regular expression contains the Global match flag g, which is quite important. First, if the regular expression contains the g flag, the match method will return an array containing all matching results. If the g flag is not included, the match method will return an array, the first element of the array is the matching string, and the subsequent elements are the contents of the capture group. If nothing is matched, null is returned.

matchAll method

the matchAll method is used to find all the content that matches the regular expression in the string and return an iterator that only receives the RegExp object. Unlike the match method, the Global match flag g must be included, otherwise an error will be reported.

Image description

The matchAll method returns an iterator, and each iteration item is an array containing the matching results. The first element of each array is the matched string, and the subsequent elements are the contents of the capture group. If nothing is matched, an empty iterator is returned.

Main differences

format requirements

this, as mentioned above, is the symbol g, the match method has no special requirements for regular expressions and can contain or not contain the g flag. The matchAll method requires that the regular expression must contain the g flag, otherwise an error will be reported.

Return Value

the return value of the match method is a RegExpMatchArrayArray or null. If the regular expression contains the g flag, the returned array contains all matching strings; If it does not contain the g flag, the returned array contains the matching strings and the contents of the capture group; And the return value of the matchAll method is an iterator, and each iteration item is an array containing the matching results. Each array contains the matched string and the contents of the capture group.

Use Scenario

the match method is suitable for simple matching operations, especially when only the first result needs to be matched or global matching is not required, while the matchAll method is suitable for scenarios where all matching results and their capturing groups need to be obtained, especially when dealing with complex regular expressions.

Mode of use

the match method

there is a simple string from which we need to extract all the numbers. Let's simply implement it:

const content = "abcd88dadghagdh66"
const regex = /\d+/g
const result = content.match(regex)
console.log( JSON.stringify(result))
Enter fullscreen mode Exit fullscreen mode

in this example, we used the match method to extract all the numbers in the string. Because the regular expression contains the g flag, the match method returns an array of all matches.

Output result:

["88","66"]
Enter fullscreen mode Exit fullscreen mode

matchAll method

there is a string from which we need to extract all dates and their components containing year, month, and day, we can do the following:

Const str="Today is 2025-03-23, tomorrow is 2025-03-24, and the day after tomorrow is 2025-03-25"
const regex = /(\d{4})-(\d{2})-(\d{2})/g
const result = Array.from(str.matchAll(regex))
result.forEach(match => {
Console.log (===Result: "+match [0]+", Year: "+match [1]+", Month: "+match [2]+", Day: "+match [3]+");
})
Enter fullscreen mode Exit fullscreen mode

in this example, we used the matchAll method to extract all the dates and their components from the string. Since the regular expression contains the g flag, the matchAll method returns an iterator, and after we convert it to an array, we can easily access each match result and its capture group.

match and matchAll make a comparison

There is a string from which you need to extract all email addresses and their username and domain name:

const str = "email,111@qq.com or aaaaa@163.com"
const regex = /(\w+)@(\w+.\w+)/g


const matchResult = str.match(regex)
console.log("===" + JSON.stringify(matchResult))


const matchAllResult = Array.from(str.matchAll(regex))
matchAllResult.forEach(match => {
  console.log("===Results: " + match[0] + ", @: " + match[1] + ", @: " + match[2] + "")
});
Enter fullscreen mode Exit fullscreen mode

let's look at the results:

Image description

in this example, the match method can only return matching email addresses, while the matchAll method can return each email address with its user name and domain name. Therefore, the matchAll method is more powerful when dealing with scenarios that require capturing groups.

Related Summary

in actual development, match and matchAll are two very common regular expression methods; The match method is suitable for simple matching operations, while the matchAll method is suitable for scenarios where all matching results and their capture groups need to be obtained.

Top comments (0)