Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c | compare string format

Tags:

c

ansi-c

I want to find out if there is any simple option to a string is equal to a format string. for example I want this format .mat[something][something] to be equal to using strcmp to .mat[r1][r2] or .mat[4][5]

Is there any option to use regular expressions of a sort? or something like strcmp(.mat[%s][%s], .mat[r3][r5])?

BTW I'm using ansi-c Thanks

like image 949
Elon Salfati Avatar asked Jun 06 '26 16:06

Elon Salfati


2 Answers

Using the closest thing to regular expression, scanf scan sets, this would work, but it is remarkably ugly:

char row[20], col[20], bracket[2], ignored;
if (sscanf(input, ".mat[%19[^]]][%19[^]]%1[]]%c", row, col, bracket, &ignored) == 3) {
    // row and col contain the corresponding specifications...    
    // bracket contains "]"
    // %c failed to convert because if the end of string
    ....
}

Here is the broken down conversion specification for ".mat[r1][r2]":

".mat["    // matches .mat[
"%19[^]]"  // matches r1   count=1
"]["       // matches ][
"%19[^]]"  // matches r2   count=2
"%1[]]"    // matches ]    count=3
"%c"       // should not match anything because of the end of string
like image 160
chqrlie Avatar answered Jun 09 '26 06:06

chqrlie


Alternative to @chqrlie fine answer: This allows for various suffixes and no bracket[2]

Use "%n" which saves the scan offset. It will be non-zero if scanning succeeded up to that point

// .mat[something][something]
#define PREFIX ".mat"
#define IDX "[%19[^]]]"
#define SUFFIX ""

char r1[20], r2[20];
int n = 0;
sscanf(input, PREFIX INDEX INDEX SUFFIX "%n", r1, r2, &n);

// Reached the end and there was no more
if (n > 0 && input[n] == '\0') Success();
else Failure();
like image 45
chux - Reinstate Monica Avatar answered Jun 09 '26 05:06

chux - Reinstate Monica



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!