C | compare string format

I want to see if there is any simple parameter for a string equal to the format string. for example, I want this format to .mat[something][something]

equal the usage strcmp

- .mat[r1][r2]

or.mat[4][5]

Is it possible to use sort regular expressions? or something like strcmp(.mat[%s][%s], .mat[r3][r5])

?

By the way, I am using ansi-c Thanks

+3


source to share


2 answers


Using the closest thing to regex, scan sets scanf

, this would work, but it's surprisingly 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
    ....
}

      



Below 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

      

+3


source


An alternative to @chqrlie's excellent answer: this allows different suffixes and notbracket[2]

Use "%n"

that saves scan offset. It will be nonzero if scanning up to this 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();

      

+1


source







All Articles