RE2库Match/PartialMatch/FindAndConsume行为差异技术问询
Great question—this behavior trip up a lot of folks new to RE2, but it all boils down to the core design intentions behind each function. Let’s break it down:
1. RE2::Match(): Full-range matching with implicit whole-match extraction
The Match() function is built to check if a specific slice (or the entire input) matches your regex. A key quirk here is that it always treats the entire matched region as the "0th group"—even when you don’t define explicit capturing groups.
In your code:
bool ret = regex.Match(sp, 0, text.size(), RE2::UNANCHORED, &submatch, 1);
The 1 tells the function you want to extract 1 group. Since your regex \d+ has no explicit groups, RE2 falls back to using the 0th group (the full matched string "123") and populates your submatch variable with it. That’s why this call succeeds even without a capturing group.
2. RE2::PartialMatch(): Find any substring match, but needs explicit groups for extraction
PartialMatch() checks if your regex matches any part of the input, but its behavior shifts when you pass output variables like &submatch:
- If you don’t pass any output variables, it will return
truejust to confirm a match exists (even with a non-capturing regex like\d+). - But if you do pass an output variable, the function expects that variable to map to an explicit capturing group in your regex. Since your original regex has no groups, there’s nothing to put into
submatch—so the function returnsfalse(it can’t fulfill the extraction request).
When you switch to (\d+), you add a 1st capturing group. Now PartialMatch() has something to populate into submatch, so it returns true.
3. RE2::FindAndConsume(): Iterative matching with explicit group extraction
This function works like PartialMatch() but advances the input StringPiece past each match. Just like PartialMatch(), if you pass an output variable (your &submatch), it requires an explicit capturing group to fill that variable.
Your original regex \d+ has no groups, so FindAndConsume() can’t extract anything to put into submatch—hence the loop never runs. Adding the capturing group (\d+) gives it a valid value to extract, so the loop works as expected.
Quick Recap
- Use
Match()when you need to check full/slice matches and want the entire matched string without explicit groups. - Use
PartialMatch()orFindAndConsume()without output variables if you only need to confirm a match exists (even without groups). - Use
PartialMatch()orFindAndConsume()with explicit capturing groups when you need to extract specific parts of the match.
内容的提问来源于stack exchange,提问作者elad-ep

