C string is a sequence of characters terminated with a null character ‘\0’. Matching a pattern in a string is a very common operation that 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)(.*) // Pattern must have Geek followed by any character
Output: Pattern matched! Pattern Matching in CTo match a pattern in a C string, we can use the POSIX regular expression library which offers support for regular expressions, allowing for more complex pattern matching within strings. We will follow the below approach to match a pattern in a string in C using the POSIX regular expression library.
Approach- First, define the text and pattern strings.
- Use the regex_t structure to create a regular expression object.
- Use regcomp to compile the regular expression.
- If the compilation fails print an error and exit.
- Use regexec to search for or match the pattern within the string.
- If the regexec returns 0 print “Pattern Matched!”.
- Finally, free regex memory using regfree function and exit.
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 Match a Pattern in a String
#include <regex.h>
#include <stdio.h>
int main()
{
// define the text to be searched
const char* text = "GeeksForGeeks";
// define the pattern to search for
const char* pattern = "Geek";
// Declare a regex_t variable to store the compiled
// regular expression
regex_t regex;
// Variable to store the return value of regex functions
int ret;
// Compile the regular expression
ret = regcomp(®ex, pattern, REG_EXTENDED);
if (ret) {
// If the compilation fails, print an error message
// and return 1
fprintf(stderr, "Could not compile regex\n");
return 1;
}
// Execute the regular expression
ret = regexec(®ex, text, 0, NULL, 0);
if (!ret) {
// If the pattern matches, print the text, pattern,
// and success message
printf("Text: %s\n", text);
printf("Pattern: %s\n", pattern);
printf("Pattern matched!\n");
}
else if (ret == REG_NOMATCH) {
// If the pattern does not match, print a failure
// message
printf("Pattern did not match\n");
}
else {
// If an error occurs, get the error message and
// print it
char msgbuf[100];
regerror(ret, ®ex, msgbuf, sizeof(msgbuf));
fprintf(stderr, "Regex match failed: %s\n", msgbuf);
return 1;
}
// Free the memory allocated to the pattern buffer by
// regcomp
regfree(®ex);
return 0;
}
OutputText: GeeksForGeeks
Pattern: Geek
Pattern matched!
Time Complexity: O(N * M), where N is the length of the text and M is the length of the text. Auxiliary Space: O(N)
Note: For handling larger texts or more complex patterns is is advisable to use more efficient string matching algorithms such as the Knuth-Morris-Pratt (KMP) algorithm or the Boyer-Moore algorithm that are designed to process larger inputs more efficiently.
|