0

I want to count the number of digits in a string which can include non digits(aa11aa1a). Can i solve this problem with a Finite State Machine? Can this problem be represented as regular expression?

What if i want to know whether the count is "X" or not, does it change the nature problem? To be more precise, is there 3 digits in this string? Is a FSM enough to solve the problem?

mert inan
  • 1,537
  • 2
  • 15
  • 26

3 Answers3

1

The second problem can be solved with a regular expression.

Consider: ^[^0-9]*[0-9][^0-9]*[0-9][^0-9]*[0-9][^0-9]*$.

You could also use groups: ^[^0-9]*([0-9][^0-9]*){3}$

I don't think you can use regular expressions alone to solve the first problem. But a solution using regular expressions (to remove all non-digits, or match a single digit) would be trivial.

cha0site
  • 10,517
  • 3
  • 33
  • 51
  • Do not we need a "\*" before {3}. so that that group can be repeated? how just{3} enables repetition like star? ^[^0-9]*([0-9][^0-9]*)*{3}$ – mert inan Jul 11 '12 at 17:19
  • @mert: No, the `{3}` itself is the reptition. It means "repeat 3 times". The general form is `{n,m}`, which means "repeats n to m times". – cha0site Jul 11 '12 at 17:22
  • one last thing 111aaaa, this string is validated successfully. But the length is not 3. So patterns annotated with "\*" does not change/increment counter? – mert inan Jul 11 '12 at 17:34
  • What do you mean, the length is not 3? There are 3 digits in the string. Also, what counter? – cha0site Jul 11 '12 at 17:42
  • 3 covers the group not only [0-9], 111aaaa -> and total length is 7 in this case. The pattern is not like this ([0-9]){3} – mert inan Jul 11 '12 at 17:48
  • @mert: Yes, in the first 2 repetitions, the `*` inside the group catches 0 non-digits. Do you want me to break the regex down and explain it? In that case, please open a new question for that. – cha0site Jul 11 '12 at 17:52
0

If you just want to match 3 digits that's like

/[^0-9]*[0-9][^0-9]*[0-9][^0-9]*[0-9][^0-9]*/

If it matches the string contains exactly three digits.

Gordon Seidoh Worley
  • 7,839
  • 6
  • 45
  • 82
0

Rather than using an explicit FSM, I'd suggest using a regular expression to take out all the non-digits and then just take the length of the resultant string. Alternatively, match your regex to individual digits and take the count of the number of matches (this would likely be less efficient, though). Or, the simplest way to do it (pseudocode):

count = 0

for char in string
    if char is a digit
        increment count

// For your second part
    if count > X
        count isn't X; done

if count < X
    count isn't X; done
else
    count is X; done
JAB
  • 20,783
  • 6
  • 71
  • 80