gpt4 book ai didi

ios - NSRegularExpression:如何从NSString中提取匹配的组?

转载 作者:行者123 更新时间:2023-12-01 18:58:47 32 4
gpt4 key购买 nike

我的代码看起来像

    NSString *pattern = @"\\w+(\\w)";
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:pattern
options:NSRegularExpressionCaseInsensitive error:nil];
NSString *testValue = @"Beer, Wine & Spirits (beer_and_wine)";
NSTextCheckingResult *match = [regex firstMatchInString:testValue options:0 range:NSMakeRange(0, testValue.length)];
for (int groupNumber=1; groupNumber<match.numberOfRanges; groupNumber+=1) {
NSRange groupRange = [match rangeAtIndex:groupNumber];
if (groupRange.location != NSNotFound)
NSLog(@"match %d: '%@'", groupNumber, [testValue substringWithRange:groupRange]);
else
NSLog(@"match %d: '%@'", groupNumber, @"");
}

我想做什么?

NSString *testValue = @"Beer, Wine & Spirits (beer_and_wine)";

我想提取 beer_and_wine
我得到什么?
当我运行此代码时,没有匹配的内容,没有任何内容被打印出来

最佳答案

要匹配beer_and_wine,可以使用以下简单的正则表达式:

(?<=\()[^()]*

参见 demo
  • 后面的(?<=\()会检查我们是否以括号开头
  • [^()]*匹配不包含括号的任何字符

  • 在代码中,如下所示:
    NSError *error = NULL;
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"(?<=\\()[^()]*" options:NSRegularExpressionAnchorsMatchLines error:&error];
    if (regex) {
    NSRange rangeOfFirstMatch = [regex rangeOfFirstMatchInString:subject options:0 range:NSMakeRange(0, [subject length])];
    if (!NSEqualRanges(rangeOfFirstMatch, NSMakeRange(NSNotFound, 0))) {
    NSString *result = [string substringWithRange:rangeOfFirstMatch];
    } else {
    // no match
    }
    } else {
    // there's a syntax error in the regex
    }

    关于ios - NSRegularExpression:如何从NSString中提取匹配的组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24398917/

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