regexec() fails to match pattern - c

I am trying to match strings like 'sdb-iof-pool 1008.56M 884K' using this regular expression: ^(.*)([\s]+)([-+]?[0-9]*\.?[0-9]+)([K|M|G|T|P]{1})([\s]+)([-+]?[0-9]*\.?[0-9]+)([K|M|G|T|P]{1})(.*)$
My c code is the following:
int reti;
regex_t regex;
size_t maxGroups = 8;
regmatch_t groupArray[maxGroups];
const char * pattern = "^(.*)([\\s]+)([-+]?[0-9]*\\.?[0-9]+)([K|M|G|T|P]{1})([\\s]+)([-+]?[0-9]*\\.?[0-9]+)([K|M|G|T|P]{1})(.*)$";
reti = regcomp(&regex, pattern, REG_EXTENDED);
if (reti) {
regerror(reti, &regex, log_buffer, IOF_MAX_MSG);
snprintf(error, IOF_MAX_MSG, "%s: Failed to compile regex '%s': (%d) '%s'", __FUNCTION__, pattern, reti, log_buffer);
return FAIL;
}
reti = regexec(&regex, cmd_output, maxGroups, groupArray, 0);
if (reti == REG_NOMATCH) {
regerror(reti, &regex, log_buffer, IOF_MAX_MSG);
regfree(&regex);
snprintf(error, IOF_MAX_MSG, "Failed to match regex '%s' on '%s': %s", pattern, cmd_output, log_buffer);
return FAIL;
}
regfree(&regex);
Even though tools like this seem to confirm that the regular expression works fine, my program returns:
"Failed to match regex '^(.)([\s]+)([-+]?[0-9].?[0-9]+)([K|M|G|T|P]{1})([\s]+)([-+]?[0-9].?[0-9]+)([K|M|G|T|P]{1})(.)$' on 'sdb-iof-pool 1008.56M 884K': No match"

After several trials and errors using the utility "grep" with the option "-E" for extended regular expression and by reading the manual of the utility I suspected that the character class [\s] was the culprit. The character class [\s] is not recognized by POSIX syntax. [:space:] must be used instead.

Related

regular expression doesnt work while execute in c

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(&regex, "([0-9a-fA-F]{8}( |$))+$", 0);
if (reti)
{
fprintf(stderr, "Could not compile regex\n");
exit(1);
}
reti = regexec(&regex, "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(&regex, "([0-9a-fA-F]{8}( |$))+$", REG_EXTENDED); // <-- See here
if (reti)
{
fprintf(stderr, "Could not compile regex\n");
exit(1);
}
reti = regexec(&regex, "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(&regex, "^[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.

Curley braces are not working in regular expression in C language

The Curly braces{} are not working in C language Regular expressions, it is always giving output as NO match , if i give correct input as "ab" or "ac". I would request to help in this case.
#include <sys/types.h>
#include <regex.h>
#include <stdio.h>
int main(int argc, char *argv[]){ regex_t regex;
int reti;
char msgbuf[100];
/* Compile regular expression */
reti = regcomp(&regex, "[a-c]{2}", 0);
if( reti ){ fprintf(stderr, "Could not compile regex\n"); return(1); }
/* Execute regular expression */
reti = regexec(&regex, "ab", 0, NULL, 0);
if( !reti ){
puts("Match");
}
else if( reti == REG_NOMATCH ){
puts("No match");
}
else{
regerror(reti, &regex, msgbuf, sizeof(msgbuf));
fprintf(stderr, "Regex match failed: %s\n", msgbuf);
return 1;
}
/* Free compiled regular expression if you want to use the regex_t again */
regfree(&regex);
return 0;
}
You are using the Basic Regular Expressions dialect that has no knowledge of the quantifier {n} in the regex.
One solution would be to supply the option REG_EXTENDED as the last argument instead of 0 when creating your regex_t object.
reti = regcomp(&regex, "[a-c]{2}", REG_EXTENDED);
See http://ideone.com/oIBXxu for a Demo of your code with my modification.
As Casimir et Hippolyte notes in the comments Basic Regular Expressions support the {} quantifier as well but the curly braces must be escaped with a \ in the regex which again has to be escaped in the C string as \\. So you can use the line
reti = regcomp(&regex, "[a-c]\\{2\\}", 0);
as well as an alternative to the solution above(running Demo with this line modified under http://ideone.com/x7vlIO).
You can check http://www.regular-expressions.info/posix.html for more information about the difference between Basic and Extended Regular Expressions.

How write a regex in c to find whether string is hex

I am trying to write a program to find whether a give string is hex or not.So the given string must contain only character in between 0-9,A-F and a-f.How can i accomplish this using C?
The program i tried is give below but the regex pattern is not working well.What will be the error in this pattern?
#include <sys/types.h>
#include <regex.h>
#include <stdio.h>
int main(int argc, char *argv[]){
regex_t regex;
int reti;
char msgbuf[100];
/* Compile regular expression */
reti = regcomp(&regex, "^[a-fA-F0-9]+$", 0);
if( reti )
{
fprintf(stderr, "Could not compile regex\n");
//exit(1);
}
/* Execute regular expression */
reti = regexec(&regex, "ABC123defG", 0, NULL, 0);
if( !reti ){
puts("Match");
}
else if( reti == REG_NOMATCH ){
puts("No match");
}
else{
regerror(reti, &regex, msgbuf, sizeof(msgbuf));
fprintf(stderr, "Regex match failed: %s\n", msgbuf);
//exit(1);
}
/* Free compiled regular expression if you want to use the regex_t again */
regfree(&regex);
return 0;
}
You need to specify REG_EXTENDED in the flags argument to regcomp. If you don't, you end up with "basic" regular expression syntax, which doesn't include the + operator, amongst other things.
It's slightly surprising that "basic" regular expressions still exist, never mind being the default. But that's backwards-compatibility for you.

POSIX regex not compiling

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(&regex, "^([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(&regex, "124.168.21.3", 0, NULL, 0);
if (!reti) {
puts("Match");
} else if (reti == REG_NOMATCH) {
puts("No match");
} else {
regerror(reti, &regex, msgbuf, sizeof(msgbuf));
fprintf(stderr, "Regex match failed: %s\n", msgbuf);
exit(1);
}
regfree(&regex);
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}$"

Regular expressions in C: examples?

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(&regex, "^a[[:alnum:]]", 0);
if (reti) {
fprintf(stderr, "Could not compile regex\n");
exit(1);
}
/* Execute regular expression */
reti = regexec(&regex, "abc", 0, NULL, 0);
if (!reti) {
puts("Match");
}
else if (reti == REG_NOMATCH) {
puts("No match");
}
else {
regerror(reti, &regex, msgbuf, sizeof(msgbuf));
fprintf(stderr, "Regex match failed: %s\n", msgbuf);
exit(1);
}
/* Free memory allocated to the pattern buffer by regcomp() */
regfree(&regex);
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(&regex, "^(-)?([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(&regex, msgbuf, 0, NULL, 0);
if (!reti) {
puts("Match");
}
else if (reti == REG_NOMATCH) {
puts("No match");
}
else {
regerror(reti, &regex, msgbuf, sizeof(msgbuf));
fprintf(stderr, "Regex match failed: %s\n", msgbuf);
exit(1);
}
/* Free memory allocated to the pattern buffer by regcomp() */
regfree(&regex);
}
}
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 (&regex, 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 (&regex, 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, &regex, NULL, 0);
print_regerror (result, length, &regex);
return EXIT_FAILURE;
}
}
/* Free the memory allocated from regcomp(). */
regfree (&regex);
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.

Resources