我想要输入字符串的特定部分
"第一个(helloWorld):最后一个"
从那个字符串我想通过正则表达式输入"helloWorld".我在用
%*[^(](%s):"
但这不符合我的目的.请有人帮我解决这个问题.
scanf函数族中的格式说明符通常不被认为是正则表达式.
但是,你可以做你想要的事情.
#include <stdio.h>
int main() {
char str[256];
scanf("First (helloWorld): last", "%*[^(](%[^)]%*[^\n]", str);
printf("%s\n", str);
return 0;
}
%*[^(] read and discard everything up to opening paren
( read and discard the opening paren
%[^)] read and store up up to (but not including) the closing paren
%*[^\n] read and discard up to (but not including) the newline
Run Code Online (Sandbox Code Playgroud)
最后一个格式说明符在上面的上下文中不是必需的sscanf,但是如果从流中读取并且您希望它位于当前行的末尾以进行下一次读取将非常有用.但请注意,换行符仍保留在流中.
而不是使用fscanf(或scanf)直接从流中读取,它总是更好地读取一行,fgets然后提取感兴趣的字段与sscanf
// Read lines, extracting the first parenthesized substring.
#include <stdio.h>
int main() {
char line[256], str[128];
while (fgets(line, sizeof line, stdin)) {
sscanf(line, "%*[^(](%127[^)]", str);
printf("|%s|\n", str);
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
样品运行:
one (two) three
|two|
four (five) six
|five|
seven eight (nine) ten
|nine|
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
11696 次 |
| 最近记录: |