The format specifiers in the scanf
family of functions are not generally considered to be a species of regular expression.
However, you can do what you want something like this.
#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
The last format specifier is not necessary in the context of the above sscanf
, but would be useful if reading from a stream and you want it positioned at the end of the current line for the next read. Note that the newline is still left in the stream, though.
Rather than use fscanf
(or scanf
) to read from a stream directly, it's pretty much always better read a line with fgets
and then extract the fields of interest with 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;
}
Sample run:
one (two) three
|two|
four (five) six
|five|
seven eight (nine) ten
|nine|