-1

How to Wirte regular expressions in c? I am making a test case on Prime No. using concept of Regular Expression in c, Following is my source code. this code should not accept any negative no.s, should not accept 0's & 1's, Should not accept decimal no.s(floating values) & neither any alphabets or characters or special symbols, I am having problem with concept of regular expression acceptance!

#include <stdio.h>
#include <string.h>
#include <regex.h>


 int main() {
  int i, n, prime, flag=0;

  char ch[10],*p;

  printf("Enter the Number to check Whether its prime or not\n");

  scanf("%s",&ch);

  if(p= strstr(ch,".")){

    printf("Decimal Values are not allowed in Prime Number!\n");

    goto error;

  }else if (ch==[A-Za-z]){

    printf("Please Enter the Numeric Value\n");

  }

  n=atoi(ch);

  printf("The Integer Type Cast Value is:%d\n",n );

  if(n<=0){

  printf("%d is not a Valid number, prime number is always positive & greater than & is not in decimal 0\n",n );

goto error;

}else{

  for(i=2; i<=n/2; ++i){

         if(n%i==0){

           flag=1;

           break;

       }
     }
   }

   if (flag==0)
       printf("%d is a prime number.",n);
   else if (flag==1)

printf("%d is not a prime number.",n);

       else

       error:printf("%s is not a Valid number, prime number is always positive & greater than & is not in decimal 0\n",ch);

  return 0;
}
  • 1
    Possible duplicate of [Regular expressions in C: examples?](http://stackoverflow.com/questions/1085083/regular-expressions-in-c-examples) – Yuriy Ivaskevych Mar 15 '17 at 13:33

1 Answers1

0

You can't simply compare a string with a regex like this: ch==[A-Za-z]. You have to prepare (compile) the regex using regcomp() and then use regexec() to match the regex against your input string.

An old example of using POSIX regex functions can be found here.

Dmitry Egorov
  • 9,542
  • 3
  • 22
  • 40