Simple c like regular expression. The regular expression is stored in a buffer, compiled and then used.
More examples of regular expression as well as other cpp examples are at:
main page.
Some of these cpp regular expression use boost library.
I was not able to install the boost on my debian wheezy.
For this example I need no installation for any package, to get it work well,
on a lenny debian machine.
- #include <sys/types.h>
- #include <regex.h>
- #include <locale.h>
- #include <stdio.h>
- #include <string.h>
- #include <nl_types.h>
- #define SLENGTH 128
- int match(char *pattern, char *string)
- {
- char message[SLENGTH];
- char *start_search;
- int error, msize, count;
- regex_t preg;
- regmatch
_t pmatch;
-
- //REG_ICASE | REG_EXTENDED);
- error = regcomp(&preg, pattern, REG_EXTENDED);
- if (error) {
- msize = regerror(error, &preg, message, SLENGTH);
- printf("%s\n", message);
- if (msize > SLENGTH)
- printf("Additional text lost\n");
- return 1;
- }
- error = regexec(&preg, string, 1, &pmatch, 0);
- if (error == REG_NOMATCH) {
- printf("No matches in string\n");
- return 1;
- } else if (error != 0) {
- msize = regerror(error, &preg, message, SLENGTH);
- printf("%s\n", message);
- if (msize > SLENGTH)
- printf("Additional text lost\n");
- return 1;
- };
- count = 1;
- start_search = string + pmatch.rm_eo;
- while (error == 0) {
- error =
- regexec(&preg, start_search, 1, &pmatch, REG_NOTBOL);
- start_search = start_search + pmatch.rm_eo;
- count++;
- printf("match at %d\n", pmatch.rm_eo);
- //Print sub match
- unsigned matchlen;
- matchlen=pmatch.rm_eo - pmatch.rm_so;
- char * submatch = new char[matchlen+1];
- strncpy(submatch, &string[pmatch.rm_so], matchlen+1);
- submatch[matchlen]='\0';
- printf("%s\n", submatch);
- delete[] submatch;
- };
- count--;
- printf("There were %d matches\n", count);
- regfree(&preg);
- }
- main()
- {
- char patt[SLENGTH], strng[SLENGTH];
- char *eol;
-
- (void)setlocale(LC_ALL, "");
-
- printf("Enter a regular expression:");
- fgets(patt, SLENGTH, stdin);
- if ((eol = strchr(patt, '\n')) != NULL)
- *eol = '\0'; /* Replace newline with null */
- else
- return 1; /* Line entered too long */
- printf("Enter string to compare\nString: ");
- fgets(strng, SLENGTH, stdin);
- if ((eol = strchr(strng, '\n')) != NULL)
- *eol = '\0'; /* Replace newline with null */
- else return 1; /* Line entered too long */
-
- match(patt, strng);
- }
|