2017-04-27 60 views
0

嗨我有字符串應該看起來像" ab_dc-05:d5ef6:aef_ "。我想檢查一下其他字符串是否是這樣的(開始時0到x空格,最後0到x空格,只有字母數字值和「:」,「 - 」,「_」。我應該用這個?順便說一句,我發現regex.h庫,但我恐怕不能包括一個,因爲我要在Windows上使用C99。C檢查字符串是否看起來像模板

謝謝

+0

你的意思是像[strcmp](http://ideone.com/x3MvMw)? – Michi

+0

@Michi可能太複雜了,如果不是不可能的話。 'strchr()'/'strpbrk()'可以更接近匹配,但是也有一些解析器必須自己添加。 –

+0

爲什麼你需要使用庫函數?檢查數組內容的簡單循環就足夠了。 – Lundin

回答

2

這是我會怎麼做,像這應該工作,這也許不是使用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

不...使用正則表達式總是更容易,因爲它只需要使用兩個函數。但是你必須知道如何使用它們。而正則表達式庫允許你也提取匹配的字段.... –