scanf 正则表达式 - C [英] scanf regex - C

查看:35
本文介绍了scanf 正则表达式 - C的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要读取一个字符串,直到写入以下序列: x :

(.....)
x

是换行符,(.....) 可以是任何可能包含其他 字符的字符.

就我所知,scanf 允许使用正则表达式,但在此模式之前我无法读取字符串.你能帮我扫描 scanf 格式字符串吗?

<小时>

我正在尝试类似的东西:

字符输入[50000];scanf(" %[^(
x
)]", 输入);

但它不起作用.

解决方案

scanf 据我所知允许使用正则表达式

不幸的是,它不允许使用正则表达式:语法接近于误导,但在 scanf 的实现中没有任何与正则表达式相似的东西.所有这些都支持正则表达式的字符类,所以%[<something>] 被隐式地视为 [.这就是为什么您对 scanf 的调用会转换为读取由 '(', ')'、'x' 和 ' ' 以外的字符组成的字符串.>

为了解决您手头的问题,您可以设置一个循环来逐个字符地读取输入.每次得到 ' ' 时,检查一下

  • 您目前看到的输入中至少有三个字符,
  • ' ' 之前的字符是 'x',并且
  • 'x'之前的字符是另一个' '

如果以上所有都为真,则您已到达预期输入序列的末尾;否则,您的循环应该继续.

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.

解决方案

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.

这篇关于scanf 正则表达式 - C的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆