c - 如何测试字符串是否遵循 C 中的给定模式?

标签 c regex

我想检查一个字符串是否遵循某种模式。我尝试了 sscanf,但没有得到想要的结果。

模式很简单:它包括:

  • 字符串“while”后跟
  • 一个或多个空格,后跟
  • 由字母字符或下划线字符组成的字符串,后跟
  • 零个或多个空格,后跟
  • 一个冒号(':'),然后是
  • 换行符('\n')

模式示例:

  • while condition_a:
  • while test_b :

我尝试了以下方法,但它不会检查该列:

sscanf(string, "while %[a-z,_]s %[:]c", test, column);

您有什么建议吗?

最佳答案

看起来很容易实现。您不需要不直观和古怪的 scanf(),也不需要不可移植的(坦率地说,可怕的)正则表达式:

int isValid(const char *s)
{
    // the string "while" followed by
    if (memcmp(s, "while", 5))
        return 0;

    s += 5;

    // one or more spaces, followed by
    if (!isspace(*s))
        return 0;

    while (isspace(*++s))
        ;

    // a string made of alpha characters or the underscore character,
    // (I assumed zero or more)
    while (isalpha(*s) || *s == '_')
        s++;

    // followed by zero or more spaces
    while (isspace(*s))
        s++;

    // followed by a column (':'),
    if (*s++ != ':')
        return 0;

    // followed by the newline character ('\n')
    if (*s++ != '\n')
        return 0;

    // here should be the end
    return !*s;
}

关于c - 如何测试字符串是否遵循 C 中的给定模式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20912166/

相关文章:

c - atol() 与 strtol()

python - JSON SCHEMA PATTERN逗号分隔列表

c - Fork 和 dup2 - 子进程未终止 - 文件描述符问题?

c - 当我返回 2 个结构时程序接收到信号 SIGTRAP

c - 线程、事件循环和大量的连接和并发

c - 使用简单的数学运算得出奇怪的结果

regex - 正则表达式在括号中查找数字,但仅在字符串的开头

ruby - 计算正则表达式效率

javascript - 正则表达式删除 '[' 和 ']' 之间的空格

regex - sed:替代模式中未转义的换行符?