How to Replace a Substring in a String using Regular Expression in C - Step by Step Examples



How to Replace a Substring in a String using Regular Expression in C ?

Answer

To replace a substring in a string using regular expressions in C, you can use the POSIX regular expression library. This involves compiling a regular expression, searching for matches, and performing the replacement.



✐ Examples

1 Replace Substring Matching a Regular Expression in a String

In this example,

  1. We include the necessary headers regex.h for regular expression functions and string.h for string handling functions.
  2. We create a function named replaceRegex to replace a substring matching a regular expression.
  3. Inside the function, we compile the regular expression using regcomp.
  4. We use regexec to find the substring that matches the pattern.
  5. If a match is found, we copy the part before the match, add the new substring, and then add the part after the match to the result.
  6. We return the modified string.
  7. We call the replaceRegex function with the original string, the regex pattern to be replaced, and the new substring.
  8. Finally, we print the modified string to the standard output.

C Program

#include <stdio.h>
#include <string.h>
#include <regex.h>

void replaceRegex(char *str, const char *pattern, const char *replacement) {
    regex_t regex;
    regmatch_t match[1];
    char buffer[256];
    char result[256];
    char *pos;

    regcomp(&regex, pattern, REG_EXTENDED);

    if (regexec(&regex, str, 1, match, 0) == 0) {
        // Copy the part before the match
        strncpy(buffer, str, match[0].rm_so);
        buffer[match[0].rm_so] = '\0';

        // Add the replacement
        strcpy(result, buffer);
        strcat(result, replacement);

        // Add the part after the match
        pos = str + match[0].rm_eo;
        strcat(result, pos);

        // Copy the result back to the original string
        strcpy(str, result);
    }

    regfree(&regex);
}

int main() {
    char str[100] = "The quick brown fox jumps over the lazy dog";
    const char *pattern = "[a-z]+";
    const char *replacement = "animal";

    replaceRegex(str, pattern, replacement);
    printf("Modified string: %s\n", str);

    return 0;
}

Output

Modified string: Tanimal quick brown fox jumps over the lazy dog

2 Replace Another Substring Matching a Regular Expression in a String

In this example,

  1. We include the necessary headers regex.h for regular expression functions and string.h for string handling functions.
  2. We create a function named replaceRegex to replace a substring matching a regular expression.
  3. Inside the function, we compile the regular expression using regcomp.
  4. We use regexec to find the substring that matches the pattern.
  5. If a match is found, we copy the part before the match, add the new substring, and then add the part after the match to the result.
  6. We return the modified string.
  7. We call the replaceRegex function with the original string, the regex pattern to be replaced, and the new substring.
  8. Finally, we print the modified string to the standard output.

C Program

#include <stdio.h>
#include <string.h>
#include <regex.h>

void replaceRegex(char *str, const char *pattern, const char *replacement) {
    regex_t regex;
    regmatch_t match[1];
    char buffer[256];
    char result[256];
    char *pos;

    regcomp(&regex, pattern, REG_EXTENDED);

    if (regexec(&regex, str, 1, match, 0) == 0) {
        // Copy the part before the match
        strncpy(buffer, str, match[0].rm_so);
        buffer[match[0].rm_so] = '\0';

        // Add the replacement
        strcpy(result, buffer);
        strcat(result, replacement);

        // Add the part after the match
        pos = str + match[0].rm_eo;
        strcat(result, pos);

        // Copy the result back to the original string
        strcpy(str, result);
    }

    regfree(&regex);
}

int main() {
    char str[100] = "The quick brown fox jumps over the lazy dog";
    const char *pattern = "quick.*fox";
    const char *replacement = "slow tortoise";

    replaceRegex(str, pattern, replacement);
    printf("Modified string: %s\n", str);

    return 0;
}

Output

Modified string: The slow tortoise jumps over the lazy dog

Summary

In this tutorial, we learned How to Replace a Substring in a String using Regular Expression in C language with well detailed examples.




More C Strings Tutorials

  1. How to Create an Empty String in C ?
  2. How to get Length of String in C ?
  3. How to get Character at Specific Index in String in C ?
  4. How to get First Character in String in C ?
  5. How to get Last Character in String in C ?
  6. How to get First N Characters in String in C ?
  7. How to get Last N Characters in String in C ?
  8. How to get Substring after Specific Character in C ?
  9. How to get Substring before Specific Character in C ?
  10. How to get Substring between two Specific Characters in C ?
  11. How to get Substring from Specific Index to End in C ?
  12. How to Iterate over Characters in String in C ?
  13. How to Iterate over Words in String in C ?
  14. How to Check if String is Empty in C ?
  15. How to Check if String contains only Alphabets in C ?
  16. How to Check if String contains only Alphabets and Numbers in C ?
  17. How to Check if String contains only Numeric Digits in C ?
  18. How to Check if a String contains given Substring in C ?
  19. How to Check if String contains specific Character in C ?
  20. How to Check if String starts with Specific Prefix in C ?
  21. How to Check if String ends with Specific Suffix in C ?
  22. How to Append a String to another String in C ?
  23. How to Append a Character to beginning of a String in C ?
  24. How to Append a Character to end of a String in C ?
  25. How to Concatenate Two Strings in C ?
  26. How to Repeat a String N Times in C ?
  27. How to Insert Character at Specific Index in String in C ?
  28. How to Replace a Substring in String in C ?
  29. How to Replace Character at Specific Index in String in C ?
  30. How to Replace All Occurrences of a Substring in a String in C ?
  31. How to Replace a Substring in a String using Regular Expression in C ?
  32. How to Split a String in C ?
  33. How to Split a String by New Line in C ?
  34. How to Split a String by Comma in C ?
  35. How to Sort Characters in String in C ?
  36. How to convert String to Lowercase in C ?
  37. How to convert String to Uppercase in C ?
  38. How to Trim a String in C ?
  39. How to convert First Character in String to Uppercase in C ?
  40. How to Reverse a String in C ?
  41. How to Remove Character at specific Index in a String in C ?
  42. How to Remove First Character in a String in C ?
  43. How to Remove Last Character in a String in C ?
  44. How to Remove first N Characters in a String in C ?
  45. How to Remove last N Characters in a String in C ?
  46. How to Remove specific Substring in C ?
  47. How to Remove specific Character from a String in C ?
  48. How to Remove All Whitespace Characters from a String in C ?
  49. How to Remove Special Characters from a String in C ?
  50. How to keep only Alphabets in a String in C ?
  51. How to Convert Integer to String in C ?
  52. How to Convert String to Integer in C ?
  53. How to convert String to Float in C ?
  54. How to convert Float to String in C ?
  55. How to check if Two Strings are Equal in C ?
  56. How to check if Two Strings are Equal ignoring case in C ?
  57. How to Compare Two Strings in C ?
  58. How to find the Characters in the First String that are not Present in the Second String in C ?
  59. How to find the Index of Substring in C ?
  60. How to find the Index of Last Occurrence of Substring in C ?
  61. How to find the Indices of All Occurrences of Substring in C ?
  62. How to get all the possible Substrings of a String in C ?
  63. How to get all the possible K length Substrings in a String in C ?