Search code examples
regexgrammarautomatanfa

Making NFA of Regex ^[a-zA-Z0-9]{3,16}$


I'm trying to make a NFA of regex ^[a-zA-Z0-9]{3,16}$. I've understood that this regex means the language will only accept strings of length 3 to 16 which may include a to z, A to Z or 0 to 9.

I've tried to make this but the main issue I'm facing is how I can make the condition that it can only go to final state if string length is 3 or 16 and gets discarded otherwise. Any help would be appreciated.

Here's my attempt in which you can see the (3,16) on state 5 which I think is not a valid way to draw a NFA.


Solution

  • Finite machine states do not have any auxiliary data. They are just a state, and all they can do is transit to another state using a fixed set of transition rules.

    You can still count up to a known finite number; you just need one state for each possible value. But you cannot "count" in any normal sense of the word. You can't see if two subsequences are the same length, for example.

    So to accept sentences of fixed length up to 16 you will need 16 states, not including the start state nor the "sink" state where you go when the input does not match. (Usually NFAs are not required to be complete, so the sink state is implicit; it is used for any input for which there is no transition.)

    That means your NFA will look roughly like this:

    sequence of 16 states

    As it happens, there is no non-determinism there, so it's also a DFA.