Let's make a "Finite State Machine" which is used to check "a*b" regular expression.
At first we must design the FSM.
class State {
protected:
State * const nextState;
bool isFinal;
public:
State( State & next, bool _isFinal ) : nextState( &next ) { isFinal = _isFinal; }
virtual State * transition( char in ) = 0;
bool isFinalState( ) { return isFinal; }
~State( ) { isFinal = false; }
};
class State1 : public State {
public:
State1( State & nextState, bool _isFinal ) : State( nextState, _isFinal ) { }
State * transition( char in );
};
State * State1::transition( char in ) {
if( in >= '0' && in <= '9' ) return this->nextState;
else return NULL;
}
class State2 : public State {
public:
State2( State & nextState, bool _isFinal ) : State( nextState, _isFinal ) { }
State * transition( char in );
};
State * State2::transition( char in ) {
if( in == '*' ) return this->nextState;
else return NULL;
}
class FSM {
State1 state1;
State2 state2;
State1 state3;
State2 final;
State * current;
public:
FSM( ) : state1( state2, false ), state2( state3, false ), state3( final, false ), final( final,true ), current( &state1 ) { }
bool run( const char *s );
};
bool FSM::run(const char *s) {
int len = strlen( s );
int i = 0;
do {
current = current->transition( s[i] );
if( current && current->isFinalState( ) )
return true;
i++;
} while( NULL != current && i < len );
return false;
}
int main() {
char s[ ] = "3*4";
FSM fsm;
if( fsm.run( s ) ) {
cout << s << " is a regular expression like \"a*b\" " << endl;
}
return 0;
}
No comments:
Post a Comment