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
在上述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;
}
示例运行:
one (two) three
|two|
four (five) six
|five|
seven eight (nine) ten
|nine|