Program to find all match of a regex in a string

Last Updated : 11 Jul, 2025

Prerequisite: smatch | Regex (Regular Expressions) in C++ Given a regex, the task is to find all regex matches in a string.

Without using iterator: 

Implementation:

CPP
// C++ program to find all the matches
#include <bits/stdc++.h>
using namespace std;
int main()
{
    string subject("My GeeksforGeeks is my "
                    "GeeksforGeeks none of your GeeksforGeeks");

    // Template instantiations for
    // extracting the matching pattern.
    smatch match;
    regex r("GeeksforGeeks");
    int i = 1;
    while (regex_search(subject, match, r)) {
        cout << "\nMatched string is " << match.str(0) << endl
            << "and it is found at position "
            << match.position(0)<<endl;
        i++;

        // suffix to find the rest of the string.
        subject = match.suffix().str();
    }
    return 0;
}
Java
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main {
  public static void main(String[] args) {
    String subject = "My GeeksforGeeks is my GeeksforGeeks none of your GeeksforGeeks";
    Pattern pattern = Pattern.compile("GeeksforGeeks");
    Matcher matcher = pattern.matcher(subject);
    int i = 1;

    while (matcher.find()) {
      System.out.println("\nMatched string is " + matcher.group(0));
      System.out.println("and it is found at position " + matcher.start());
      i++;

      // suffix to find the rest of the string.
      subject = subject.substring(matcher.end());
      matcher = pattern.matcher(subject);
    }
  }
}
Python3
# Python program to find all the matches
import re

subject = "My GeeksforGeeks is my GeeksforGeeks none of your GeeksforGeeks"

# Template instantiations for
# extracting the matching pattern.
match = re.search("GeeksforGeeks", subject)
i = 1

while match:
    print("\nMatched string is", match.group(0))
    print("and it is found at position", match.start())
    i += 1

    # suffix to find the rest of the string.
    subject = subject[(match.end()):]
    match = re.search("GeeksforGeeks", subject)
C#
using System;
using System.Text.RegularExpressions;

class Program
{
    static void Main(string[] args)
    {
        string subject = "My GeeksforGeeks is my GeeksforGeeks none of your GeeksforGeeks";
        
       // Template instantiations for
       // extracting the matching pattern.
        Regex r = new Regex("GeeksforGeeks");
        Match match;
        int i = 1;
        while ((match = r.Match(subject)).Success)
        {
            Console.WriteLine("\nMatched string is " + match.Value
                                + "\nand it is found at position " + match.Index);
            i++;

            // suffix to find the rest of the string.
            subject = subject.Substring(match.Index + match.Length);
        }
    }
}
JavaScript
// JavaScript program to find all the matches
let subject = "My GeeksforGeeks is my GeeksforGeeks none of your GeeksforGeeks";
let match = subject.match("GeeksforGeeks");
let i = 1;

// loop to find the rest of the string
while (match) {
    console.log("\nMatched string is", match[0]);
    console.log("and it is found at position", match.index);
    i += 1;

    // suffix to find the rest of the string
    subject = subject.substring(match.index + match[0].length);
    match = subject.match("GeeksforGeeks");
}

Output
Matched string is GeeksforGeeks
and it is found at position 3

Matched string is GeeksforGeeks
and it is found at position 7

Matched string is GeeksforGeeks
and it is found at position 14
  • Note: Above code is running perfectly fine but the problem is input string will be lost.
  • Using iterator: Object can be constructed by calling the constructor with three parameters: a string iterator indicating the starting position of the search, a string iterator indicating the ending position of the search, and the regex object. Construct another iterator object using the default constructor to get an end-of-sequence iterator. 

Implementation:

C++
#include <bits/stdc++.h>
using namespace std;
int main()
{
    string subject("geeksforgeeksabcdefghg"
                "eeksforgeeksabcdgeeksforgeeks");

    // regex object.
    regex re("geeks(for)geeks");

    // finding all the match.
    for (sregex_iterator it = sregex_iterator(subject.begin(), subject.end(), re);
        it != sregex_iterator(); it++) {
        smatch match;
        match = *it;
        cout << "\nMatched string is = " << match.str(0)
            << "\nand it is found at position "
            << match.position(0) << endl;
        cout << "Capture " << match.str(1)
            << " at position " << match.position(1) << endl;
    }
    return 0;
}
Java
import java.util.regex.*;

public class Main {
    public static void main(String[] args)
    {
        String subject
            = "geeksforgeeksabcdefghgeeksforgeeksabcdgeeksforgeeks";

        // regex pattern
        Pattern pattern
            = Pattern.compile("geeks(for)geeks");

        // finding all matches
        Matcher matcher = pattern.matcher(subject);
        while (matcher.find()) {
            System.out.println(
                "\nMatched string is = " + matcher.group(0)
                + "\nand it is found at position "
                + matcher.start());
            System.out.println("Capture " + matcher.group(1)
                               + " at position "
                               + matcher.start(1));
        }
    }
}
Python3
import re

subject = "geeksforgeeksabcdefghgeeksforgeeksabcdgeeksforgeeks"

# regex pattern.
pattern = r"geeks(for)geeks"

# finding all the matches.
matches = re.finditer(pattern, subject)
for match in matches:
    print(f"\nMatched string is = {match.group(0)}\nand it is found at position {match.start(0)}")
    print(f"Capture {match.group(1)} at position {match.start(1)}")
C#
using System;
using System.Text.RegularExpressions;

class MainClass {
    public static void Main()
    {
        string subject
            = "geeksforgeeksabcdefghgeeksforgeeksabcdgeeksforgeeks";

        // Regex object
        Regex re = new Regex("geeks(for)geeks");

        // Finding all the match
        foreach(Match match in re.Matches(subject))
        {
            Console.WriteLine("\nMatched string is = "
                              + match.Value);
            Console.WriteLine("and it is found at position "
                              + match.Index);
            Console.WriteLine(
                "Capture " + match.Groups[1].Value
                + " at position " + match.Groups[1].Index);
        }
    }
}
JavaScript
let subject = "geeksforgeeksabcdefghgeeksforgeeksabcdgeeksforgeeks";

// Regex pattern
let pattern = /geeks(for)geeks/g;

// Finding all the matches
let match;
while ((match = pattern.exec(subject)) !== null) {
  console.log("\nMatched string is = " + match[0]);
  console.log("and it is found at position " + match.index);
  console.log(
    "Capture " + match[1]
    + " at position " + (match.index + match[0].indexOf(match[1]))
  );
}

Output
Matched string is = geeksforgeeks
and it is found at position 0
Capture for at position 5

Matched string is = geeksforgeeks
and it is found at position 21
Capture for at position 26

Matched string is = geeksforgeeks
and it is found at position 38
Capture for at position 43
Comment