iOS Objective-C 宏判断字符串是文本还是链接
您可以将以下代码封装成一个宏,用于判断字符串是文本还是链接:
#define isTextOrURL(string) [YourClassName isURL:string]
@interface YourClassName : NSObject
+ (BOOL)isURL:(NSString *)string;
@end
@implementation YourClassName
+ (BOOL)isURL:(NSString *)string {
NSError *error = NULL;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:'(http|https)://([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)?' options:NSRegularExpressionCaseInsensitive error:&error];
NSTextCheckingResult *match = [regex firstMatchInString:string options:0 range:NSMakeRange(0, [string length])];
return match != nil;
}
@end
然后,您可以在其他地方使用宏 isTextOrURL 来判断字符串是否是文本或链接。例如:
NSString *inputString = 'http://www.example.com';
if (isTextOrURL(inputString)) {
NSLog('The string is a URL.');
} else {
NSLog('The string is not a URL.');
}
请注意,您需要将 YourClassName 替换为您实际使用的类名。
原文地址: https://www.cveoy.top/t/topic/qjjq 著作权归作者所有。请勿转载和采集!