2017-08-08 63 views
3

我想知道是否有任何一个字符串的简单选项等于格式字符串。 比如我想这种格式.mat[something][something]等于使用strcmp.mat[r1][r2].mat[4][5]c |比较字符串格式

是否有使用排序的正则表达式的任何选项?或类似strcmp(.mat[%s][%s], .mat[r3][r5])

BTW我使用的是ANSI-C 感谢

+0

ansi-c不支持正则表达式。如果您在Posix系统上,则可以使用POSIX正则表达式。 – SergeyA

+1

你想要正则表达式,而不是字符串比较。 –

回答

3

使用最接近的正则表达式,scanf扫描台,这会工作,但它是非常难看:

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 
    .... 
} 

这里是为".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 
+0

也许''.mat [%19 [^]] [%19 [^]]%1 []]%c“'(1 less']') – chux

+1

@chux:令人惊讶的不可读是不是?需要第三个']来匹配字符串中的']'。第二部分不存在,因为'%1 []]'匹配字符串中的第二个']'。 – chqrlie

+0

同意3']]]'为了提高可读性'#define INDEX“%19 [^]]”...“.mat [”INDEX“] [”INDEX“%1 []]%c”' – chux

1

替代@chqrlie细ANS wer:这允许各种后缀并且没有bracket[2]

使用"%n"可以保存扫描偏移量。如果扫描成功直到该点将为非零值

// .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();