Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
641 views
in Technique[技术] by (71.8m points)

scanf regex - C

I needed to read a string until the following sequence is written: x :

(.....)

x

is the new line character and (.....) can be any characters that may include other characters.

scanf allows regular expressions as far as I know, but i can't make it to read a string untill this pattern. Can you help me with the scanf format string?


I was trying something like:

char input[50000];
scanf(" %[^(
x
)]", input);

but it doesn't work.

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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 ' '.

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

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

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...