Regex Capture Groups

Counting Regex Matches

How can you count the number of matches found in a string using regex?

Abstract art representing computer programming

Counting the number of regex matches in a string can be accomplished using std::sregex_iterator. This iterator allows you to iterate through all matches of a regex pattern in a string.

Using std::sregex_iterator

Here’s a simple example of how to count matches:

#include <iostream>
#include <regex>

int main() {
  std::string input = "one two three four five";
  std::regex pattern("\\b\\w+\\b");

  auto words_begin = std::sregex_iterator(
    input.begin(), input.end(), pattern);
  auto words_end = std::sregex_iterator();

  int count = std::distance(words_begin, words_end);
  std::cout << "Number of words: " << count;
}
Number of words: 5

In this example, the regex pattern "\b\w+\b" matches individual words in the string. We use std::sregex_iterator to iterate through all matches and std::distance to count them.

Detailed Example

Here’s another example that counts specific patterns, such as digits:

#include <iostream>
#include <regex>

int main() {
  std::string input =
    "There are 3 cats, 4 dogs, and 5 birds.";
  std::regex pattern("\\d");

  auto numbers_begin = std::sregex_iterator(
    input.begin(), input.end(), pattern);
  auto numbers_end = std::sregex_iterator();

  int count = std::distance(
    numbers_begin, numbers_end);
  std::cout << "Number of digits: " << count;
}
Number of digits: 3

In this case, the regex pattern "\d" matches individual digits. The process is the same: create an iterator for the matches and use std::distance to count them.

Summary

Counting regex matches in a string is straightforward with std::sregex_iterator. This iterator provides a way to traverse all matches of a pattern, and std::distance helps count them. This method is efficient and works well for both simple and complex patterns.

Answers to questions are automatically generated and may not have been reviewed.

A computer programmer
Part of the course:

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Free, unlimited access

This course includes:

  • 124 Lessons
  • 550+ Code Samples
  • 96% Positive Reviews
  • Regularly Updated
  • Help and FAQ
Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2024 - All Rights Reserved