Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <string.h>
- #include <stdlib.h>
- #define PCRE2_CODE_UNIT_WIDTH 8
- #include <pcre2.h>
- int main(int argc, char const *argv[])
- {
- pcre2_code *compileCode;
- PCRE2_SPTR pattern; /* PCRE2_SPTR is a pointer to unsigned code units of */
- PCRE2_SPTR subject;
- PCRE2_SPTR replace;
- size_t subjectLength;
- size_t replaceLength;
- int subsCount;
- PCRE2_UCHAR *output = (PCRE2_UCHAR *)malloc(sizeof(PCRE2_UCHAR));
- PCRE2_SIZE outputLength;
- int errornumber;
- PCRE2_SIZE errorOffset;
- if (argc != 4) {
- printf("Usage: ./app <pattern> <replace> <subject>\n");
- return EXIT_FAILURE;
- }
- pattern = (PCRE2_SPTR)argv[1];
- replace = (PCRE2_SPTR)argv[2];
- subject = (PCRE2_SPTR)argv[3];
- subjectLength = strlen((char *)subject);
- replaceLength = strlen((char *)replace);
- compileCode = pcre2_compile(
- pattern, /* the pattern */
- PCRE2_ZERO_TERMINATED, /* indicates pattern is zero-terminated */
- 0, /* default options */
- &errornumber, /* for error number */
- &errorOffset, /* for error offset */
- NULL /* use default compile context */
- );
- if (compileCode == NULL) {
- PCRE2_UCHAR buffer[256];
- pcre2_get_error_message(errornumber, buffer, sizeof(buffer));
- printf("PCRE2 compilation failed at offset %d: %s\n", (int)errorOffset, buffer);
- pcre2_code_free(compileCode);
- free(output);
- return EXIT_FAILURE;
- }
- subsCount = pcre2_substitute(
- compileCode, /*Points to the compiled pattern*/
- subject, /*Points to the subject string*/
- PCRE2_ZERO_TERMINATED, /*subjectLength,*/ /*Length of the subject string*/
- 0, /*Offset in the subject at which to start matching*/
- PCRE2_SUBSTITUTE_GLOBAL | PCRE2_SUBSTITUTE_OVERFLOW_LENGTH | PCRE2_SUBSTITUTE_EXTENDED, /*Option bits*/
- NULL, /*Points to a match data block, or is NULL*/
- NULL, /*Points to a match context, or is NULL*/
- replace, /*Points to the replacement string*/
- PCRE2_ZERO_TERMINATED, /*replaceLength,*/ /*Length of the replacement string*/
- output, /*Points to the output buffer*/
- &outputLength /*Points to the length of the output buffer*/
- );
- if (subsCount > 0) {
- printf("%s\ncount: %i\n", output, subsCount);
- } else if (subsCount == 0) {
- printf("No matches\n");
- } else {
- PCRE2_UCHAR buffer[256];
- pcre2_get_error_message(subsCount, buffer, sizeof(buffer));
- printf("PCRE2 substitute failed. ErrorCode %i: %s\n", (int)subsCount, buffer);
- pcre2_code_free(compileCode);
- free(output);
- return EXIT_FAILURE;
- }
- pcre2_code_free(compileCode);
- free(output);
- return EXIT_SUCCESS;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement