2011-02-14 61 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"); 
} 
相关问题