用正则表达式使用scanf [英] Use scanf with Regular Expressions

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

问题描述

我一直在尝试在scanf上使用正则表达式,以便读取最多n个字符的字符串,并丢弃任何其他字符,直到新行字符为止。应将任何空格视为常规字符,因此包含在要读取的字符串中。
我研究过关于正则表达式的维基百科文章,但是我无法使scanf正常工作。以下是我尝试过的一些代码:

I've been trying to use regular expressions on scanf, in order to read a string of maximum n characters and discard anything else until the New Line Character. Any spaces should be treated as regular characters, thus included in the string to be read. I've studied a Wikipedia article about Regular Expressions, yet I can't get scanf to work properly. Here is some code I've tried:

scanf("[ ]*%ns[ ]*[\n]", string);

[]应该是实际的空格字符,*应该是一个或多个, n是要读取的字符数,string是使用malloc分配的指针。
我尝试了几种不同的组合;然而,我倾向于只得到一个句子的第一个单词(在空格字符处停止)。此外,*似乎丢弃一个字符而不是零或更多的含义...

[ ] is supposed to go for the actual space character, * is supposed to mean one or more, n is the number of characters to read and string is a pointer allocated with malloc. I have tried several different combinations; however I tend to get only the first word of a sentence read (stops at space character). Furthermore, * seems to discard a character instead of meaning "zero or more"...

有没有人可以详细解释scanf如何解释正则表达式?更重要的是,是否有效地重复使用getc?

Could anybody explain in detail how regular expressions are interpreted by scanf? What is more, is it efficient to use getc repetitively instead?

感谢提前:D

推荐答案

简短的回答: scanf 不正确地处理正则表达式。

The short answer: scanf does not handle regular expressions literally speaking.

如果你想在C中使用正则表达式,可以使用正则表达式POSIX库。有关此库用法的基本示例,请参阅以下问题: C中的正则表达式:示例? a>

If you want to use regular expressions in C, you could use the regex POSIX library. See the following question for a basic example on this library usage : Regular expressions in C: examples?

现在,如果你想这样做 scanf 的方式,你可以尝试像

Now if you want to do it the scanf way you could try something like

scanf("%*[ ]%ns%*[ ]\n",str);

n 替换为%ns 通过从输入流读取的最大字符数。
%* [] 部分要求忽略任何空格。您可以将 * 替换为特定的数字,以忽略精确的字符数。您可以在大括号之间添加其他字符,以忽略不仅仅是空格。

Replace the n in %ns by the maximal number of characters to read from input stream. The %*[ ] part asks to ignore any spaces. You could replace the * by a specific number to ignore a precise number of characters. You could add other characters between braces to ignore more than just spaces.

不确定上述scanf是否可以正常工作,因为空格也与 %s 指令。

我一定会用一个 fgets 调用,然后用类似于以下:
如何修剪前导/尾随空格以标准方式?

Not sure if the above scanf would work as spaces are also matched with the %s directive.
I would definitely go with a fgets call, then triming the surrounding whitespaces with something like the following: How do I trim leading/trailing whitespace in a standard way?

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

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