Click here to Skip to main content
15,905,616 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
i want to validate a string pattern using c


pattern 123-456-789 i.e position 3 & 7 should be dash and others should be numeric value

i am validating it as below as below

C++
for( int iny = 0; iny < ilength ; iny++ )
    {

        if(isdigit((pszSeqCodeObjName[iny]) && ((iny != 3  || iny != 7))
        {
            validation= true;
        }
       else 
        {
           if(pszSeqCodeObjName[3] == '-'|| pszSeqCodeObjName[7] =='-')
            {
                 validation= true;
            }
            else
            {
              validation= false;

            }



suggest if any better logic can be done

quick response highly Appreciated !!.
Posted
Updated 9-Mar-16 10:23am
v2
Comments
jeron1 9-Mar-16 13:54pm    
What happens if you put a '3' in position 3?

C++
static bool match(const char *text, const char *pattern)
{
    while (*text && *pattern)
    {
        switch (*pattern)
        {
            case '#':
                if ( !isdigit(*text) )
                    return false;
            default:
                if (*pattern != *text)
                    return false;
        }
        text++;
        pattern++;
    }
    return *text == 0 && *pattern == 0;
}

int main(int, char **)
{
    const char text[] = "123-45-6789";
    const char pattern[] = "###-##-####";
    printf("%s applied to %s returns %d.\n", pattern, text, match(text, pattern));
    return 0;
}
 
Share this answer
 
v2
I would simplify it a little:
C++
bool valid = true;
for (int i = 0; i < iLength && valid; i++)
    {
    if (i == 3 || i == 7)
        {
        valid = pszSeqCodeObjName[i] == '-';
        }
    else
        {
        valid = isdigit(pszSeqCodeObjName[i]);
        }
    }
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900