2011-02-14 57 views

回答

7

如果您需要手工做(從wikipedia信息):

  1. 檢查長度(36,包括連字符)
  2. 檢查的連字符是在預期的位置(9 -14-19-24)
  3. 檢查所有其他的字符是十六進制(isxdigit
3

您可以使用正則表達式來查看它是否符合GUID格式。

+0

多數民衆贊成在.NET c#中很容易。不知道如何在C++中做到這一點。應該使用哪個庫在C++中使用正則表達式。你有代碼示例嗎? – Sapna 2011-02-14 13:58:24

+1

boost :: regex是最明顯的選擇:http://www.boost.org/doc/libs/release/libs/regex/ – stefaanv 2011-02-14 14:06:03

2

嘗試下面的代碼 - 可以幫助。

_bstr_t sGuid(_T("guid to validate")); 
GUID guid; 

if(SUCCEEDED(::CLSIDFromString(sGuid, &guid)) 
{ 
    // Guid string is valid 
} 
+0

當我只通過任何指導時,這似乎不起作用......它試圖獲得該分類顯然不存在,因此失敗。 – Sapna 2011-02-14 15:51:22

1

這裏的情況下,你仍然需要一個代碼示例:P

#include <ctype.h> 
using namespace std; 
bool isUUID(string uuid) 
{ 
    /* 
    * Check if the provided uuid is valid. 
    * 1. The length of uuids should always be 36. 
    * 2. Hyphens are expected at positions {9, 14, 19, 24}. 
    * 3. The rest characters should be simple xdigits. 
    */ 
    int hyphens[4] = {9, 14, 19, 24}; 
    if (uuid.length() != 36) 
    { 
     return false;//Oops. The lenth doesn't match. 
    } 
    for (int i = 0, counter = 0; i < 36; i ++) 
    { 
     char var = uuid[i]; 
     if (i == hyphens[counter] - 1)// Check if a hyphen is expected here. 
     { 
      // Yep. We need a hyphen here. 
      if (var != '-') 
      { 
       return false;// Oops. The character is not a hyphen. 
      } 
      else 
      { 
       counter++;// Move on to the next expected hyphen position. 
      } 
     } 
     else 
     { 
      // Nope. The character here should be a simple xdigit 
      if (isxdigit(var) == false) 
      { 
       return false;// Oops. The current character is not a hyphen. 
      } 
     } 
    } 
    return true;// Seen'em all! 
} 
0

這種方法利用了scanf解析器和作品也以純C:

#include <stdio.h> 
#include <string.h> 
int validateUUID(const char *candidate) 
{ 
    int tmp; 
    const char *s = candidate; 
    while (*s) 
     if (isspace(*s++)) 
      return 0; 
    return s - candidate == 36 
     && sscanf(candidate, "%4x%4x-%4x-%4x-%4x-%4x%4x%4x%c", 
     &tmp, &tmp, &tmp, &tmp, &tmp, &tmp, &tmp, &tmp, &tmp) == 8; 
} 

測試與如:

int main(int argc, char *argv[]) 
{ 
    if (argc > 1) 
     puts(validateUUID(argv[1]) ? "OK" : "Invalid"); 
} 
相關問題