It comes to a point when the phrase Regular Expressions might be a good hint towards a good solution, if the input is to be 100% verified.
Code:
#include <regex.h>
#include <stdio.h>
#include <stdlib.h>
int main()
{
/* Regular expression to match a US phone number */
char phonePattern[] = "[(]([0-9]{3})[)] ([0-9]{3})-([0-9]{4})";
char testS[] = "For more information call (345) 123-4567.";
regmatch_t *found;
regex_t regx;
/* Compile the expression in phonePattern to a regex_t */
regcomp(®x, phonePattern, REG_EXTENDED);
/* Allocate memory for the bracketed parts of the expression */
found = malloc( (regx.re_nsub+1) * sizeof(*found) );
if( regexec(®x, testS, regx.re_nsub + 1, found, 0) == 0 )
{
int i;
/* At found[0] the indices for the entire match are stored
* so, if we don't need it we better start of found[1]
*/
for(i = 1; i <= regx.re_nsub; i++)
{
printf("Piece of phone #%d: <", i);
fwrite(testS+found[i].rm_so, 1, found[i].rm_eo - found[i].rm_so, stdout);
printf(">\n");
}
}
free(found);
return 0;
}
The non standard POSIX compliant <regex.h> header usually comes with a typical installation of gcc.
For a Regular Expression library that is free and ported for Windows, one can always get it from:
http://www.pcre.org/