使用 scanf() 将标识符读入 C 程序
我需要我的 C 程序能够使用 C 中的 scanf() 方法读取标识符。
在这种情况下,标识符是一个字母或 _ 字符,后跟一个或多个字母数字字符(包括 _ 字符)。
正则表达式将是
[a-ZA-Z_][a-zA-Z0-9_]*
这些是正确标识符的示例:
_identifier1
variable21
这些是错误标识符的示例
12var
%foobar
有谁知道如何在 C 中使用 scanf() 来完成此操作?
I need my C program to be able to read in an identifier using the scanf() method in C.
An identifier in this case is a letter or a _ character followed by one or more alphanumeric characters including the _ character.
The regular expression would be
[a-ZA-Z_][a-zA-Z0-9_]*
These are examples of correct identifiers:
_identifier1
variable21
These are examples of incorrect identifiers
12var
%foobar
Does anybody know how this would be done using scanf() in C?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
scanf()
不支持正则表达式。标准 C 库中根本不支持正则表达式。您必须读取字符串,然后“手动”解析它。例如:
输出:
scanf()
doesn't support regular expressions. There's no regular expression support at all in the standard C library. You'll have to read a string and then parse it "manually".For example:
Output:
scanf
的格式说明符有点有限。它们不能用于识别您的标识符的模式。我相信您只能对读取的字符串执行自定义验证,例如:(我还没有测试过这个,但它应该说明这个想法)
scanf
's format specifiers are kind of limited. They cannot be used to identify the pattern of your identifier. I believe you can only perform custom validation on the read string, something like:(I haven't tested this but it should illustrate the idea)
如果您习惯使用正则表达式,为什么不直接使用正则表达式库呢?如果您使用的是 POSIX 兼容操作系统,则应该有一个正则表达式库。
If you're comfortable with using regex why not just use a regex library? If you're using a POSIX compliant operating system there should be a regex library.