[ create a new paste ] login | about

Link: http://codepad.org/Rl3PcWiQ    [ raw code | output | fork ]

C++, pasted on Aug 21:
// Taken from beautiful code.

#include <stdio.h>

/*
 
 Character	Meaning
 c	Matches any literal character c.
 . (period)	Matches any single character.
 ^	Matches the beginning of the input string.
 $	Matches the end of the input string.
 *	Matches zero or more occurrences of the previous character.
 
*/

#define TRUE 1
#define FALSE 0


int match(char const *regexp, char const *text);
int matchhere(char const *regexp, char const *text);
int matchstar(int c, char const *regexp, char const *text);

/* match: search for regexp anywhere in text */
int match(char const *regexp, char const *text)
{
    if (regexp[0] == '^')
        return matchhere(regexp+1, text);
    do {    /* must look even if string is empty */
        if (matchhere(regexp, text))
            return 1;
    } while (*text++ != '\0');
    return 0;
}

/* matchhere: search for regexp at beginning of text */
int matchhere(char const *regexp, char const *text)
{
    if (regexp[0] == '\0')
        return 1;
    if (regexp[1] == '*')
        return matchstar(regexp[0], regexp+2, text);
    
    if (regexp[0] == '$' && regexp[1] == '\0')
        return *text == '\0';
    if (*text!='\0' && (regexp[0]=='.' || regexp[0]==*text))
        return matchhere(regexp+1, text+1);
    return 0;
}

/* matchstar: search for c*regexp at beginning of text */
int matchstar(int c, char const *regexp, char const *text)
{
    do {   /* a * matches zero or more instances */
        if (matchhere(regexp, text))
            return 1;
    } while (*text != '\0' && (*text++ == c || c == '.'));
    return 0;
}

void test(char const* re, char const* string, int expectedReturn) {
    
    printf("Testing re: %s string: %s expectedReturn: %i\n",
        re, string, expectedReturn);
    
    int actualReturn = match(re, string);
    
    if(actualReturn == expectedReturn) {
        printf("Test suceeded.\n");
    } else {
        printf("Test failed, returned %i instead!\n", 
            actualReturn);
    }    
}


int main() {
    
    test("b*ch", "bitch", FALSE);
    test("b.*ch", "bitch", TRUE);
    
    return 0;
}


Output:
1
2
3
4
Testing re: b*ch string: bitch expectedReturn: 0
Test failed, returned 1 instead!
Testing re: b.*ch string: bitch expectedReturn: 1
Test suceeded.


Create a new paste based on this one


Comments: