I've tested the following regular expression at http://www.regexpal.com/
([A-Z]{1}[a-z]+)+([_]{1}([A-Z]{1}[a-z]+)+)+[.][a-z]+
Which successfully matches the following file names:
Butter_Butter.jpg
JavaPiebald_Java_Piebald.jpg
LowWhitePied_Pied.jpg
Piebald_Piebald.jpg
SpinnerBlast_Spider_Pinstripe_Pastel.jpg
Caramel_Caramel.jpg
LightningPied_Pied_Axanthic.jpg
Pastel_Pastel.jpg
Spider_Spider.jpg
Spinner_Spider_Pinstripe.jpg
When I implement the regular expression in the following C code, I receive no matches:
#define COLLECTION_REGEX "([A-Z]{1}[a-z]+)+([_]{1}([A-Z]{1}[a-z]+)+)+[.][a-z]+"
int is_valid_filename(char *filename)
{
regex_t regex;
int i, match;
char msgbuf[100];
match = 1;
i = regcomp(®ex, COLLECTION_REGEX, 0);
if (i)
{
perror("Could not compile regex");
}
else
{
match = regexec(®ex, filename, 0, NULL, 0);
if (!match)
{
puts("Match");
}
else if (match == REG_NOMATCH)
{
puts("No match");
}
else
{
regerror(match, ®ex, msgbuf, sizeof(msgbuf));
puts(msgbuf);
}
}
regfree(®ex);
return match;
}
Subsequent execution:
./a.out
No match
No match
No match
No match
No match
No match
No match
No match
No match
No match
The regular expression appears correct, I am uncertain as to why I am obtaining these results.
Output from GDB:
Breakpoint 1, is_valid_filename (filename=0x609050 "Piebald_Piebald.jpg") at crp-web-builder.c:76
76 match = regexec(®ex, filename, 0, NULL, 0);
(gdb) continue
Continuing.
No match
Breakpoint 1, is_valid_filename (filename=0x609460 "LightningPied_Pied_Axanthic.jpg") at crp-web-builder.c:76
76 match = regexec(®ex, filename, 0, NULL, 0);
(gdb) continue
Continuing.
No match
Breakpoint 1, is_valid_filename (filename=0x609870 "SpinnerBlast_Spider_Pinstripe_Pastel.jpg") at crp-web-builder.c:76
76 match = regexec(®ex, filename, 0, NULL, 0);
(gdb) continue
Continuing.
No match
Thanks to Jonathan Leffler. The line:
i = regcomp(®ex, COLLECTION_REGEX, 0);
Should be:
i = regcomp(®ex, COLLECTION_REGEX, REG_EXTENDED);
Related
i am trying to build regular expression with the regex.h lib.
i checked my expression in https://regex101.com/ with the the input
"00001206 ffffff00 00200800 00001044" and i checked it in python as well, both gave me the expected result.
when i ran the code below in c (over unix) i got "no match" print.
any one have any suggest?
regex_t regex;
int reti;
reti = regcomp(®ex, "([0-9a-fA-F]{8}( |$))+$", 0);
if (reti)
{
fprintf(stderr, "Could not compile regex\n");
exit(1);
}
reti = regexec(®ex, "00001206 ffffff00 00200800 00001044", 0, NULL, 0);
if (!reti)
{
printf("Match");
}
else if (reti == REG_NOMATCH) {
printf("No match bla bla\n");
}
Your pattern contains a $ anchor, capturing groups with (...) and the interval quantifier {m,n}, so you need to pass REG_EXTENDED to the regex compile method:
regex_t regex;
int reti;
reti = regcomp(®ex, "([0-9a-fA-F]{8}( |$))+$", REG_EXTENDED); // <-- See here
if (reti)
{
fprintf(stderr, "Could not compile regex\n");
exit(1);
}
reti = regexec(®ex, "00001206 ffffff00 00200800 00001044", 0, NULL, 0);
if (!reti)
{
printf("Match");
}
else if (reti == REG_NOMATCH) {
printf("No match bla bla\n");
}
See the online C demo printing Match.
However, I believe you need to match the entire string, and disallow whitespace at the end, so probably
reti = regcomp(®ex, "^[0-9a-fA-F]{8}( [0-9a-fA-F]{8})*$", REG_EXTENDED);
will be more precise as it will not allow any arbitrary text in front and won't allow a trailing space.
I have this code for matching an IP address pattern. But it doesn't seem to work and I don't know why. It always prints on the terminal "No match"
regex_t regex;
int reti;
char msgbuf[100];
reti = regcomp(®ex, "^([0-9]{1,3}).([0-9]{1,3}).([0-9]{1,3}).([0-9]{1,3})$", 0);
if (reti) {
fprintf(stderr, "Could not compile regex\n");
exit(1);
}
reti = regexec(®ex, "124.168.21.3", 0, NULL, 0);
if (!reti) {
puts("Match");
} else if (reti == REG_NOMATCH) {
puts("No match");
} else {
regerror(reti, ®ex, msgbuf, sizeof(msgbuf));
fprintf(stderr, "Regex match failed: %s\n", msgbuf);
exit(1);
}
regfree(®ex);
Any idea?
I found it, in fact I should specify the cflags field of the regcomp function to REG_EXTENDED and not 0.
You should escape the dots. And you probably don't need the capturing groups. Replace
"^([0-9]{1,3}).([0-9]{1,3}).([0-9]{1,3}).([0-9]{1,3})$"
with
"^[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}$"
I want to match a group recursively using PCRE C library.
e.g.
pattern = "(\d,)"
subject = "5,6,3,2,"
OVECCOUNT = 30
pcrePtr = pcre_compile(pattern, 0, &error, &erroffset, NULL);
rc = pcre_exec(pcrePtr, NULL, subject, (int)strlen(subject),
0, 0, ovector, OVECCOUNT);
rc is -1..
How to match all groups so that matches are "5,", "6,", "3,", "2,"
For analogy, PHP's preg_match_all parses entire string until the end of subject...
Any way I used strtok since "," was repeating after each group..
Solution using pcre is welcomed....
Try this :
pcre *myregexp;
const char *error;
int erroroffset;
int offsetcount;
int offsets[(0+1)*3]; // (max_capturing_groups+1)*3
myregexp = pcre_compile("\\d,", 0, &error, &erroroffset, NULL);
if (myregexp != NULL) {
offsetcount = pcre_exec(myregexp, NULL, subject, strlen(subject), 0, 0, offsets, (0+1)*3);
while (offsetcount > 0) {
// match offset = offsets[0];
// match length = offsets[1] - offsets[0];
if (pcre_get_substring(subject, &offsets, offsetcount, 0, &result) >= 0) {
// Do something with match we just stored into result
}
offsetcount = pcre_exec(myregexp, NULL, subject, strlen(subject), 0, offsets[1], offsets, (0+1)*3);
}
} else {
// Syntax error in the regular expression at erroroffset
}
I believe the comments are self explanatory?
I'm after some simple examples and best practices of how to use regular expressions in ANSI C. man regex.h does not provide that much help.
Regular expressions actually aren't part of ANSI C. It sounds like you might be talking about the POSIX regular expression library, which comes with most (all?) *nixes. Here's an example of using POSIX regexes in C (based on this):
#include <regex.h>
regex_t regex;
int reti;
char msgbuf[100];
/* Compile regular expression */
reti = regcomp(®ex, "^a[[:alnum:]]", 0);
if (reti) {
fprintf(stderr, "Could not compile regex\n");
exit(1);
}
/* Execute regular expression */
reti = regexec(®ex, "abc", 0, NULL, 0);
if (!reti) {
puts("Match");
}
else if (reti == REG_NOMATCH) {
puts("No match");
}
else {
regerror(reti, ®ex, msgbuf, sizeof(msgbuf));
fprintf(stderr, "Regex match failed: %s\n", msgbuf);
exit(1);
}
/* Free memory allocated to the pattern buffer by regcomp() */
regfree(®ex);
Alternatively, you may want to check out PCRE, a library for Perl-compatible regular expressions in C. The Perl syntax is pretty much that same syntax used in Java, Python, and a number of other languages. The POSIX syntax is the syntax used by grep, sed, vi, etc.
This is an example of using REG_EXTENDED.
This regular expression
"^(-)?([0-9]+)((,|.)([0-9]+))?\n$"
Allows you to catch decimal numbers in Spanish system and international. :)
#include <regex.h>
#include <stdlib.h>
#include <stdio.h>
regex_t regex;
int reti;
char msgbuf[100];
int main(int argc, char const *argv[])
{
while(1){
fgets( msgbuf, 100, stdin );
reti = regcomp(®ex, "^(-)?([0-9]+)((,|.)([0-9]+))?\n$", REG_EXTENDED);
if (reti) {
fprintf(stderr, "Could not compile regex\n");
exit(1);
}
/* Execute regular expression */
printf("%s\n", msgbuf);
reti = regexec(®ex, msgbuf, 0, NULL, 0);
if (!reti) {
puts("Match");
}
else if (reti == REG_NOMATCH) {
puts("No match");
}
else {
regerror(reti, ®ex, msgbuf, sizeof(msgbuf));
fprintf(stderr, "Regex match failed: %s\n", msgbuf);
exit(1);
}
/* Free memory allocated to the pattern buffer by regcomp() */
regfree(®ex);
}
}
It's probably not what you want, but a tool like re2c can compile POSIX(-ish) regular expressions to ANSI C. It's written as a replacement for lex, but this approach allows you to sacrifice flexibility and legibility for the last bit of speed, if you really need it.
man regex.h doesn't show any manual entry for regex.h, but man 3 regex shows a page explaining the POSIX functions for pattern matching.
The same functions are described in The GNU C Library: Regular Expression Matching, which explains that the GNU C Library supports both the POSIX.2 interface and the interface the GNU C Library has had for many years.
For example, for an hypothetical program that prints which of the strings passed as argument matches the pattern passed as first argument, you could use code similar to the following one.
#include <errno.h>
#include <regex.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void print_regerror (int errcode, size_t length, regex_t *compiled);
int
main (int argc, char *argv[])
{
regex_t regex;
int result;
if (argc < 3)
{
// The number of passed arguments is lower than the number of
// expected arguments.
fputs ("Missing command line arguments\n", stderr);
return EXIT_FAILURE;
}
result = regcomp (®ex, argv[1], REG_EXTENDED);
if (result)
{
// Any value different from 0 means it was not possible to
// compile the regular expression, either for memory problems
// or problems with the regular expression syntax.
if (result == REG_ESPACE)
fprintf (stderr, "%s\n", strerror(ENOMEM));
else
fputs ("Syntax error in the regular expression passed as first argument\n", stderr);
return EXIT_FAILURE;
}
for (int i = 2; i < argc; i++)
{
result = regexec (®ex, argv[i], 0, NULL, 0);
if (!result)
{
printf ("'%s' matches the regular expression\n", argv[i]);
}
else if (result == REG_NOMATCH)
{
printf ("'%s' doesn't the regular expression\n", argv[i]);
}
else
{
// The function returned an error; print the string
// describing it.
// Get the size of the buffer required for the error message.
size_t length = regerror (result, ®ex, NULL, 0);
print_regerror (result, length, ®ex);
return EXIT_FAILURE;
}
}
/* Free the memory allocated from regcomp(). */
regfree (®ex);
return EXIT_SUCCESS;
}
void
print_regerror (int errcode, size_t length, regex_t *compiled)
{
char buffer[length];
(void) regerror (errcode, compiled, buffer, length);
fprintf(stderr, "Regex match failed: %s\n", buffer);
}
The last argument of regcomp() needs to be at least REG_EXTENDED, or the functions will use basic regular expressions, which means that (for example) you would need to use a\{3\} instead of a{3} used from extended regular expressions, which is probably what you expect to use.
POSIX.2 has also another function for wildcard matching: fnmatch(). It doesn't allow to compile the regular expression, or get the substrings matching a sub-expression, but it is very specific for checking when a filename match a wildcard (e.g. it uses the FNM_PATHNAME flag).
While the answer above is good, I recommend using PCRE2. This means you can literally use all the regex examples out there now and not have to translate from some ancient regex.
I made an answer for this already, but I think it can help here too..
Regex In C To Search For Credit Card Numbers
// YOU MUST SPECIFY THE UNIT WIDTH BEFORE THE INCLUDE OF THE pcre.h
#define PCRE2_CODE_UNIT_WIDTH 8
#include <stdio.h>
#include <string.h>
#include <pcre2.h>
#include <stdbool.h>
int main(){
bool Debug = true;
bool Found = false;
pcre2_code *re;
PCRE2_SPTR pattern;
PCRE2_SPTR subject;
int errornumber;
int i;
int rc;
PCRE2_SIZE erroroffset;
PCRE2_SIZE *ovector;
size_t subject_length;
pcre2_match_data *match_data;
char * RegexStr = "(?:\\D|^)(5[1-5][0-9]{2}(?:\\ |\\-|)[0-9]{4}(?:\\ |\\-|)[0-9]{4}(?:\\ |\\-|)[0-9]{4})(?:\\D|$)";
char * source = "5111 2222 3333 4444";
pattern = (PCRE2_SPTR)RegexStr;// <<<<< This is where you pass your REGEX
subject = (PCRE2_SPTR)source;// <<<<< This is where you pass your bufer that will be checked.
subject_length = strlen((char *)subject);
re = 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 */
/* Compilation failed: print the error message and exit. */
if (re == 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);
return 1;
}
match_data = pcre2_match_data_create_from_pattern(re, NULL);
rc = pcre2_match(
re,
subject, /* the subject string */
subject_length, /* the length of the subject */
0, /* start at offset 0 in the subject */
0, /* default options */
match_data, /* block for storing the result */
NULL);
if (rc < 0)
{
switch(rc)
{
case PCRE2_ERROR_NOMATCH: //printf("No match\n"); //
pcre2_match_data_free(match_data);
pcre2_code_free(re);
Found = 0;
return Found;
// break;
/*
Handle other special cases if you like
*/
default: printf("Matching error %d\n", rc); //break;
}
pcre2_match_data_free(match_data); /* Release memory used for the match */
pcre2_code_free(re);
Found = 0; /* data and the compiled pattern. */
return Found;
}
if (Debug){
ovector = pcre2_get_ovector_pointer(match_data);
printf("Match succeeded at offset %d\n", (int)ovector[0]);
if (rc == 0)
printf("ovector was not big enough for all the captured substrings\n");
if (ovector[0] > ovector[1])
{
printf("\\K was used in an assertion to set the match start after its end.\n"
"From end to start the match was: %.*s\n", (int)(ovector[0] - ovector[1]),
(char *)(subject + ovector[1]));
printf("Run abandoned\n");
pcre2_match_data_free(match_data);
pcre2_code_free(re);
return 0;
}
for (i = 0; i < rc; i++)
{
PCRE2_SPTR substring_start = subject + ovector[2*i];
size_t substring_length = ovector[2*i+1] - ovector[2*i];
printf("%2d: %.*s\n", i, (int)substring_length, (char *)substring_start);
}
}
else{
if(rc > 0){
Found = true;
}
}
pcre2_match_data_free(match_data);
pcre2_code_free(re);
return Found;
}
Install PCRE using:
wget https://ftp.pcre.org/pub/pcre/pcre2-10.31.zip
make
sudo make install
sudo ldconfig
Compile using :
gcc foo.c -lpcre2-8 -o foo
Check my answer for more details.
I'm trying to create a collection of regexes in C, with no much success.
Currently I'm trying to find include statements with the following regex:
(#include <.+>)|(#include \".+\")
here is my code:
#include <stdio.h>
#include <stdlib.h>
#include <regex.h>
char *regex_str = "(#include <.+>)|(#include \".+\")";
char *str = "#include <stdio.h>";
regex_t regex;
int reti;
int main() {
/* Compile Regex */
reti = regcomp(®ex, regex_str, 0);
if (reti) {
printf("Could not compile regex.\n");
exit(1);
}
/* Exec Regex */
reti = regexec(®ex, str, 0, NULL, 0);
if (!reti) {
printf("Match\n");
} else if (reti == REG_NOMATCH) {
printf("No Match\n");
} else {
regerror(reti, ®ex, str, sizeof(str));
printf("Regex match failed: %s\n", str);
exit(1);
}
/* Free compiled regular expression if you want to use the regex_t again */
regfree(®ex);
return 0;
}
The result I get is: No Match
What am I doing wrong?
You might need to escape your match group:
char *regex_str = "\\(#include [\"<].*[\">]\\)";
Which could likely be rolled into one pattern.