boozi
boozi

Reputation: 506

Regular expressions with scanf in C

I'm trying to achieve the following without any success:

Removing the opening

message "

and trailing

"

while leaving the content in between, and saving it into my variable, using sscanf regular expressions. I wrote the following code:

sscanf( buffer, "message \"%[^\"]", message)

Which works good when I have something like message "Hey there", but when I'm trying the following string, I get only the white space between the two quotation marks.

message " """ This is a Test """ "

The result for this should be """ This is a Test """

Is there a way to upgrade my expression so it will include this extreme event of message? I tried to look it up both in google and here, and couldn't find an elegant answer. I'm aware that it's possible using string manipulation with a lot lines of code, but I'm trying something more simple here.

P.S. The trailing " is the end of the expression, and is a must by the program, after that comes nothing.

Thanks in advance for the feedback!

Upvotes: 4

Views: 858

Answers (1)

flogram_dev
flogram_dev

Reputation: 42868

If you're fine with not using regex for the whole thing:

Original version:

sscanf(buffer, "message \"%[^$]", message); // remove 'message "'
message[strlen(message) - 1] = '\0'; // remove trailing '"'

Safe, correct, and generic version:

char* buffer = ...;
const char* prefix = "message \"";
const char* suffix = "\"";

if (strstr(buffer, prefix) != buffer) {
    // error, doesn't start with `prefix`
}

buffer += strlen(prefix);

char* suffixStart = strrchr(buffer, suffix[0]);
if (!suffixStart || strcmp(suffixStart, suffix) != 0) {
    // error, doesn't end with `suffix`
}

*suffixStart = '\0'; // strip `suffix`

Upvotes: 2

Related Questions