gpt4 book ai didi

ios - NSRegularExpression 无法正常工作

转载 作者:行者123 更新时间:2023-12-02 01:52:20 24 4
gpt4 key购买 nike

嗨,我遇到了问题,如果字符串中没有电话号码,并且 NSRegularExpression 找不到任何内容,则应用程序崩溃,但当它确实找到电话号码时,它在字符串中工作正常,没有任何问题。我怎样才能阻止它崩溃。

NSRegularExpression *phoneexpression = [NSRegularExpression regularExpressionWithPattern:@"\\d{4}-\\d{4}"options:NSRegularExpressionCaseInsensitive error:NULL];
NSString *phString = TextString;
NSString *PH = [phString substringWithRange:[phoneexpression rangeOfFirstMatchInString:phString options:NSMatchingCompleted range:NSMakeRange(0, [phString length])]];

我认为这就是问题所在

NSString *PH = [phString substringWithRange:[phoneexpression rangeOfFirstMatchInString:phString options:NSMatchingCompleted range:NSMakeRange(0, [phString length])]];

最佳答案

我猜你会得到一个 NSRangeException。

尝试这样:

NSString *PH = nil;
NSRegularExpression *phoneexpression = [NSRegularExpression regularExpressionWithPattern:@"\\d{4}-\\d{4}"options:NSRegularExpressionCaseInsensitive error:NULL];
NSString *phString = TextString;
NSRange rg = [phoneexpression rangeOfFirstMatchInString:phString options:NSMatchingCompleted range:NSMakeRange(0, [phString length])];

if(rg.location != NSNotFound)
PH = [phString substringWithRange:rg];

在将返回的范围传递给 substringWithRange 之前检查它很重要。有关详细信息,请参阅此引用:https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/#//apple_ref/occ/instm/NSString/substringWithRange :

编辑:另请检查 rangeOfFirstMatchInString 返回的范围是否违反引用文献中记录的边界限制:

Raises an NSRangeException if (aRange.location - 1) or (aRange.location + aRange.length - 1) lies beyond the end of the receiver.

关于ios - NSRegularExpression 无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26650331/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com