gpt4 book ai didi

objective-c - 使用 NSRegularExpression 从正则表达式中提取部分

转载 作者:行者123 更新时间:2023-12-04 03:27:21 27 4
gpt4 key购买 nike

我想用 NSRegularExpression 提取字符串的一部分。

例如,我有这个字符串:

@"1   UIKit                               0x00540c89 -[UIApplication _callInitializationDelegatesForURL:payload:suspended:] + 1163";

我想提取“UIKit”、“0x00540c89”、“UIApplication”、“_callInitializationDelegatesForURL:payload:suspended:”和“1163”。

我做了正则表达式:

@"^[0-9]+\\s+[a-zA-Z]+\\s+0x[0-9a-zA-Z]+\\s+\\-\\s*\\[[a-zA-Z]+\\s+[_:a-zA-Z]+\\]\\s+\\+\\s+[0-9]+"

但是我不知道我该怎么做。这是可能的。

    NSString *origen = @"1   UIKit                               0x00540c89 -[UIApplication _callInitializationDelegatesForURL:payload:suspended:] + 1163";
// Setup an NSError object to catch any failures
NSError *error = NULL;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"^[0-9]+\\s+[a-zA-Z]+\\s+0x[0-9a-zA-Z]+\\s+\\-\\s*\\[[a-zA-Z]+\\s+[_:a-zA-Z]+\\]\\s+\\+\\s+[0-9]+"
options:NSRegularExpressionCaseInsensitive
error:&error];
// create an NSRange object using our regex object for the first match in the string
NSRange rangeOfFirstMatch = [regex rangeOfFirstMatchInString:origen options:0 range:NSMakeRange(0, [origen length])];
// check that our NSRange object is not equal to range of NSNotFound
if (!NSEqualRanges(rangeOfFirstMatch, NSMakeRange(NSNotFound, 0))) {
// Since we know that we found a match, get the substring from the parent string by using our NSRange object
NSString *substringForFirstMatch = [origen substringWithRange:rangeOfFirstMatch];
NSLog(@"Extracted: %@",substringForFirstMatch);
}

最佳答案

试试这个:

NSCharacterSet *separatorSet = [NSCharacterSet characterSetWithCharactersInString:@" -[]+?.,"];
NSMutableArray *array = [origen componentsSeparatedByCharactersInSet:separatorSet];
[array removeObject:@""];

关于objective-c - 使用 NSRegularExpression 从正则表达式中提取部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9601551/

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