3

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

Elon Salfati
  • 1,537
  • 6
  • 23
  • 46

2 Answers2

3

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
chqrlie
  • 131,814
  • 10
  • 121
  • 189
1

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();
chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256