如何使用NSRegularExpression或Objective-C中的任何其他有效方式来检查GUID(或UUID)的有效性 [英] How to check the validity of a GUID (or UUID) using NSRegularExpression or any other effective way in Objective-C

查看:104
本文介绍了如何使用NSRegularExpression或Objective-C中的任何其他有效方式来检查GUID(或UUID)的有效性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果NSString类似于@"{A5B8A206-E14D-429B-BEB0-2DD0575F3BC0}",则该方法应返回TRUE,而对于@@"bla bla bla"这样的NSString则返回FALSE.

The method should return TRUE if the NSString is something like @"{A5B8A206-E14D-429B-BEB0-2DD0575F3BC0}" and FALSE for a NSString like @"bla bla bla"

我正在使用类似的东西:

I am using something like:

- (BOOL)isValidGUID {

    NSError *error;

    NSRange range = [[NSRegularExpression regularExpressionWithPattern:@"(?:(\\()|(\\{))?\\b[A-F0-9]{8}(?:-[A-F0-9]{4}){3}-[A-Z0-9]{12}\\b(?(1)\\))(?(2)\\})" options:NSRegularExpressionCaseInsensitive error:&error] rangeOfFirstMatchInString:self.GUID options:0 range:NSMakeRange(0, [self.GUID length])];

    if (self.GUID && range.location != NSNotFound && [self.GUID length] == 38) {

        return TRUE;

    } else {

        return NO;
    }
}

但是它没有按我预期的那样工作.

but it is not working as I have expected.

重要:我正在使用的GUID用大括号括起来,例如:{A5B8A206-E14D-429B-BEB0-2DD0575F3BC0}

Important: GUID which I am using is enclosed by curly braces like this: {A5B8A206-E14D-429B-BEB0-2DD0575F3BC0}

推荐答案

此正则表达式与我匹配

\A\{[A-F0-9]{8}-[A-F0-9]{4}-[A-F0-9]{4}-[A-F0-9]{4}-[A-F0-9]{12}\}\Z

简而言之:

  • \A\Z是字符串的开头和结尾
  • \{\}被逃脱了卷曲的bracets
  • [A-F0-9]{8}正好是0、1、2、3、4、5、6、7、8、9,A,B,C,D,E,F的8个字符
  • \A and \Z is the beginning and end of the string
  • \{ and \} is escaped curly bracets
  • [A-F0-9]{8} is exactly 8 characters of either 0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F

作为NSRegularExpression,它看起来像这样

As an NSRegularExpression it would look like this

NSError *error = NULL;
NSRegularExpression *regex = 
  [NSRegularExpression regularExpressionWithPattern:@"\\A\\{[A-F0-9]{8}-[A-F0-9]{4}-[A-F0-9]{4}-[A-F0-9]{4}-[A-F0-9]{12}\\}\\Z" 
                                            options:NSRegularExpressionAnchorsMatchLines 
                                              error:&error];
// use the regex to match the string ...

这篇关于如何使用NSRegularExpression或Objective-C中的任何其他有效方式来检查GUID(或UUID)的有效性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆