【问题标题】:c | compare string formatc |比较字符串格式
【发布时间】:2018-01-16 06:59:59
【问题描述】:

我想知道是否有任何简单的字符串选项等于格式字符串。 例如,我希望这种格式 .mat[something][something] 等于使用 strcmp.mat[r1][r2].mat[4][5]

有没有使用某种正则表达式的选项?或类似strcmp(.mat[%s][%s], .mat[r3][r5])

顺便说一句,我正在使用 ansi-c 谢谢

【问题讨论】:

  • ansi-c 不支持正则表达式。如果您在 Posix 系统上,则可以使用 POSIX 正则表达式。
  • 你想要正则表达式,而不是字符串比较。

标签: c ansi-c


【解决方案1】:

使用最接近正则表达式的东西,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

【讨论】:

  • 可能".mat[%19[^]][%19[^]]%1[]]%c"(少1个]
  • @chux:令人惊讶的是不可读,不是吗?需要第三个] 来匹配字符串中的]。第二部分不存在,因为%1[]] 匹配字符串中的第二个]
  • 同意 3 ]]] 提高可读性#define INDEX "%19[^]]" ... ".mat[" INDEX "][" INDEX "%1[]]%c"
【解决方案2】:

替代@chqrlie 很好的答案:这允许各种后缀并且没有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();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-12-05
    • 1970-01-01
    • 1970-01-01
    • 2021-11-19
    • 2016-02-08
    • 2013-11-22
    • 1970-01-01
    相关资源
    最近更新 更多