我想检查一个字符串是否遵循某种模式。我尝试了 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/