Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • C++ Data Types
  • C++ Input/Output
  • C++ Arrays
  • C++ Pointers
  • C++ OOPs
  • C++ STL
  • C++ Interview Questions
  • C++ Programs
  • C++ Cheatsheet
  • C++ MCQ
  • C++ Projects
  • C++ Exception Handling
  • C++ Memory Management
Open In App
Next Article:
How to Reverse a String in C++?
Next article icon

How to Match a Pattern in a String in C++?

Last Updated : 04 Mar, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In C++, strings are sequences of characters stored in a char array. Matching a pattern in a string involves searching for a specific sequence of characters (the pattern) within a given string. In this article, we will learn how to match a pattern in a string in C++.

Example:

Input:
Text: "GeeksForGeeks"
Pattern: "(Geek)(.*)" // Geek followed by any characterOutput:
Pattern matched!

Pattern Matching in C++

To match a pattern in a string we can use regular expressions, which provide a powerful and flexible way to describe and match patterns within strings. C++ provides the <regex> library, which offers support for regular expressions, allowing for more complex pattern matching.

Approach:

  • Use the std::regex class to create a regular expression object, passing the pattern as a parameter to the constructor.
  • Use std::regex_search or std::regex_match to search for or match the pattern within the string.
  • If a match is found print pattern matched.

C++ Program to Match a Pattern in a String

The below program demonstrates how we can match a pattern in a string in C++.

C++
// C++ Program to show how to match a pattern in a string #include <iostream> #include <regex> #include <string> using namespace std;  int main() {     string text = "GeeksForGeeks";      // Define the regular expression pattern to match     regex pattern(         "(Geek)(.*)"); // Geek followed by any character      // Check if the entire string matches the pattern     if (regex_match(text, pattern)) {         // If matched, print message         cout << "Pattern found!" << endl;     }     else {         // If not matched, print message         cout << "Pattern not found!" << endl;     }      return 0; } 

Output
Pattern found!  

Time Complexity: O(N), here N is the size of the input string.
Auxiliary Space: O(1)

Note: For larger texts or more complex patterns, consider using more efficient string matching algorithms like the Knuth-Morris-Pratt (KMP) algorithm or the Boyer-Moore algorithm. These algorithms can handle larger inputs more effectively.


Next Article
How to Reverse a String in C++?
author
susobhanakhuli19
Improve
Article Tags :
  • C++ Programs
  • C++
  • cpp-string
  • CPP Examples
Practice Tags :
  • CPP

Similar Reads

  • How to Reverse a String in Place in C++?
    In C++, reversing a string is a basic operation in programming that is required in various applications, from simple and complex algorithms. Reversing a string in place involves changing the characters of the string directly without using input-dependent additional storage. In this article, we learn
    2 min read
  • How to Split a String into an Array in C++?
    In C++, splitting a string into an array of substrings means we have to parse the given string based on a delimiter and store each substring in an array. In this article, we will learn how to split a string into an array of substrings in C++. Example: Input: str= “Hello, I am Geek from geeksforgeeks
    2 min read
  • How to Reverse a String in C++?
    Reversing a string means replacing the first character with the last character, second character with the second last character and so on. In this article, we will learn how to reverse a string in C++. Examples Input: str = "Hello World"Output: dlroW olleHExplanation: The last character is replaced
    2 min read
  • How to Read File into String in C++?
    In C++, file handling allows us to read and write data to an external file from our program. In this article, we will learn how to read a file into a string in C++. Reading Whole File into a C++ StringTo read an entire file line by line and save it into std::string, we can use std::ifstream class to
    2 min read
  • How to Replace Text in a String Using Regex in C++?
    Regular expressions or what we can call regex for short are sequences of symbols and characters that create a search pattern and help us to find specific patterns within a given text. In this article, we will learn how to replace text in a string using regex in C++. Example Input: str = "Hello, Worl
    2 min read
  • How to Split a C++ String into a Vector of Substrings?
    In C++, splitting a string into a vector of substrings means we have to split the given string into a substring based on a given delimiter and store each substring in a vector. In this article, we will learn how to split a string into a vector of substrings in C++. Example: Input: str= "Hello, I am
    2 min read
  • How to Parse Mathematical Expressions in a C++ String?
    In C++, strings are sequences of characters stored in a char array. Strings are used to store words and text. We can also store mathematical expressions in this string. In this article, we will explore how to parse mathematical expressions in a C++ String. Example: Input:expression = (3 + 4) * 2 / (
    5 min read
  • Array of Pointers to Strings in C++
    In C++, an array is a homogeneous collection of data that is stored in a contiguous memory location. We can store almost all types of data as array elements. In this article, we will learn how to store the array of pointers to strings in C++. Array of Pointers to Strings in C++A pointer to a string
    6 min read
  • How to Take Multiple Line String Input in C++?
    In C++, taking string input is a common practice but the cin is only able to read the input text till whitespace. In this article, we will discuss how to read the multiple line of text input in C++. For Example, Input:Enter Your Text: This is amultiline text.Output:You Have Entered:This is amultilin
    2 min read
  • How to Handle Multiple String Inputs with Spaces in C++?
    In C++, strings are a sequence of characters that might contain spaces in many cases but we can read only the input text till whitespace using cin. In this article, we will learn how to handle multiple string inputs with spaces in C++. Example: Input:Enter multiple strings:String1String2Output:You E
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences