I’m always confused by the results I get when match, matchAll, regular expressions with a G flag and regular expressions without a G flag intersect. Today, let’s take a look at the results of match plus G, match without G, matchAll plus G, and matchAll without G.
match
andmatchAll
The difference between
1. Match returns an array, or null if there are no matches. MatchAll returns an iterator that needs to be traversed to see the result.
2. Stop matching after the first matching item is matched. MatchAll will matchAll the matches in the string.
The role of the G flag in regular expressions
The G flag indicates a global search. If the regular expression is defined without g modifier, only the first matching result is returned. Otherwise, all matches are returned.
The sample
Above, it can be seen that match and matchAll, plus g mark and without G mark, these two groups seem to have similarities and similarities. What are the differences between them?
Description:
1. For match, if there is a G modifier in the regular expression, the result returns a list of all strings that match the regular expression. Capture items are ignored!
2. For match, if there is no G modifier in the regular expression, the result will return not only the first match, but also all of its capture items!
3. For matchAll, if the regular expression has g modification, the iteration items it returns are arrays one by one. The array contains not only the complete string matching and all the captured items, but also the three attributes index, input and groups. Input represents the raw string of input, and groups is an object containing all groups.
4. For matchAll, if the regular expression is not decorated with G, the resulting information is exactly the same as described in Point 3. However, there is only one iteration item, that is, the first matching item.