Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

POSIX regex alternate not working

Tags:

regex

I'm using | for alternatives but it's not working. Am I doing something wrong?

Thanks!

The following code always return No match:

#include <sys/types.h>
#include <regex.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>

int main(int argc, char *argv[]){
        regex_t regex;
        int reti;
        char msgbuf[100];

/* Compile regular expression */
        reti = regcomp(&regex, "ab(c|d)", 0);
        if( reti ){ fprintf(stderr, "Could not compile regex\n"); exit(1); }

/* Execute regular expression */
        reti = regexec(&regex, "abd", 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;

}
like image 329
ethanjyx Avatar asked Oct 12 '13 01:10

ethanjyx


People also ask

What is POSIX in RegEx?

POSIX bracket expressions are a special kind of character classes. POSIX bracket expressions match one character out of a set of characters, just like regular character classes. They use the same syntax with square brackets.

Can RegEx replace characters?

RegEx can be effectively used to recreate patterns. So combining this with . replace means we can replace patterns and not just exact characters.

What is the regular expression for the strings that do not end with 01 ∑ ={ 0 1?

All strings not ending in 01: + 0 + 1 + (0 + 1)*(00 + 10 + 11). The expression +0+1 describes the strings with length zero or one, and the expression (0 + 1)*(00 + 10 + 11) describes the strings with length two or more.

What is an invalid RegEx?

An invalid pattern in a regular expression literal is a SyntaxError when the code is parsed, but an invalid string in RegExp constructors throws a SyntaxError only when the code is executed.


1 Answers

As the POSIX manual says, you need to set the flags argument to allow extended regular expressions.

   REG_EXTENDED
          Use POSIX Extended Regular Expression syntax  when  interpreting
          regex.   If  not  set,  POSIX Basic Regular Expression syntax is
          used.
like image 166
Brad Lanam Avatar answered Oct 05 '22 23:10

Brad Lanam