-3

I want to add validation for a car registration number. I have declared it as a char and it must be formatted by yyDnnnn. For example, 99D2005.

I can imagine it is straight forward, is it like the charAt() method in Java?

3 Answers3

1

No, you cannot do that in C. In C you could:

  • Use a regular expression parser (see the regcomp function); or

  • Compare the individual characters and use functions like isalpha, isdigit

There are no doubt many other ways of doing it too, but what you suggest is not one of them.

abligh
  • 24,573
  • 4
  • 47
  • 84
0

It's not that straightforward.

You'll need to loop over your string verifying each position. Something like this:

int i;
char currC;
for(i = 0;i < strlen(carReg);i++) {
    currC = tolower(carReg[i]);
    if(i < 2 && isalpha(currC)) //continue...
}
Mauren
  • 1,955
  • 2
  • 18
  • 28
0

I would use a regex library. Here is a SO link to an answer involving POSIX regexes: Regular expressions in C: examples?

Here is a small example demonstrating what I think you want to do (Linux):

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

int main(int argc, char *argv[]) {
        regex_t regex;
        int rc;
        rc = regcomp(&regex, "^[0-9]{2}[D][0-9]{4}$", REG_EXTENDED);
        if(rc != 0) {
                printf("could not compile regex\n");
                return 1;
        }

        rc = regexec(&regex, "15D1234", 0, NULL, 0);
        if(rc == 0) {
                printf("test 1 pass: match\n");
        } else {
                printf("test 1 fail\n");
        }
        regfree(&regex);
        return 0;
}
Community
  • 1
  • 1
emsworth
  • 1,149
  • 10
  • 21