C检查字符串是否看起来像模板
问题描述:
嗨我有字符串应该看起来像" ab_dc-05:d5ef6:aef_ "
。我想检查一下其他字符串是否是这样的(开始时0到x空格,最后0到x空格,只有字母数字值和“:”,“ - ”,“_”。我应该用这个?顺便说一句,我发现regex.h库,但我恐怕不能包括一个,因为我要在Windows上使用C99。C检查字符串是否看起来像模板
谢谢
答
这是我会怎么做,像这应该工作,这也许不是使用RE容易:
bool matchPattern(const char *s)
{
// Zero or more spaces at the start.
while(*s == ' ')
++s;
const char * const os = s;
while(isalnum((unsigned int) *s) || *s == ':' || *s == '-' || *s == '_')
++s;
// If middle part was empty, fail.
if(s == os)
return false;
// Zero or more spaces at the end.
while(*s == ' ')
++s;
// The string must end here, or we fail.
return *s == '\0';
}
以上尚未经过测试,但至少应该足以作为灵感
+0
不...使用正则表达式总是更容易,因为它只需要使用两个函数。但是你必须知道如何使用它们。而正则表达式库允许你也提取匹配的字段.... –
你的意思是像[strcmp](http://ideone.com/x3MvMw)? – Michi
@Michi可能太复杂了,如果不是不可能的话。 'strchr()'/'strpbrk()'可以更接近匹配,但是也有一些解析器必须自己添加。 –
为什么你需要使用库函数?检查数组内容的简单循环就足够了。 – Lundin