scanf regex – C

scanf allows regular expressions as far as I know

Unfortunately, it does not allow regular expressions: the syntax is misleadingly close, but there is nothing even remotely similar to the regex in the implementation of scanf. All that’s there is a support for character classes of regex, so %[<something>] is treated implicitly as [<something>]*. That’s why your call of scanf translates into read a string consisting of characters other than '(', ')', 'x', and '\n'.

To solve your problem at hand, you can set up a loop that read the input character by character. Every time you get a '\n', check that

  • You have at least three characters in the input that you’ve seen so far,
  • That the character immediately before '\n' is an 'x', and
  • That the character before the 'x' is another '\n'

If all of the above is true, you have reached the end of your anticipated input sequence; otherwise, your loop should continue.

Leave a Comment