【问题标题】:How to get matches in iOS using regular expression?如何使用正则表达式在 iOS 中获取匹配项?
【发布时间】:2010-11-15 13:33:09
【问题描述】:

我得到了一个类似“stackoverflow.html”的字符串,并且在正则表达式“stack(.).html”中,我希望在 (.) 中有值。

我只能找到像这样的 NSPredicate:

NSString    *string     = @"stackoverflow.html";
NSString    *expression = @"stack(.*).html";
NSPredicate *predicate  = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", expression];
BOOL match = [predicate evaluateWithObject:string]

但是,当我使用 NSRegularExpression 时,这只会告诉我得到了一个匹配项并且不会返回一个字符串:

NSRange range = [string rangeOfString:expression options:NSRegularExpressionSearch|NSCaseInsensitiveSearch];
if (range.location == NSNotFound) return nil;

NSLog (@"%@", [string substringWithRange:(NSRange){range.location, range.length}]);

它将返回总字符串 stackoverflow.html,但我只对 (.*) 中的内容感兴趣。我想恢复“溢出”。在 PHP 中这很容易做到,但是如何在 xCode for iOS 中完成呢?

如果我会这样做,从逻辑上讲:

NSInteger firstPartLength  = 5;
NSInteger secondPartLength = 5;
NSLog (@"%@", [string substringWithRange:(NSRange){range.location + firstPartLength, range.length - (firstPartLength + secondPartLength)}]

它给了我属性结果“溢出”。但问题是在很多情况下我不知道第一部分或第二部分的长度。那么有没有办法获得应该在 (.*) 中的值?

或者我必须通过找到 (.) 的位置并从那里计算第一部分和第二部分来决定选择最丑陋的方法吗?但是在正则表达式中,您可能也有 ([a-z]) 但是使用另一个正则表达式获取 () 之间值的位置然后使用它来计算左右部分的丑陋方式?如果我有更多会发生什么?像“A (.) 应该找到 (.*) 的答案。”我想要一个数组作为结果,其中值 [0] A 之后的值和 [1] to 之后的值。

我希望我的问题很清楚。

提前致谢,

【问题讨论】:

    标签: iphone regex xcode


    【解决方案1】:

    在 iOS 4.0+ 中,你可以使用NSRegularExpression:

    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"stack(.*).html" options:0 error:NULL];
    NSString *str = @"stackoverflow.html";
    NSTextCheckingResult *match = [regex firstMatchInString:str options:0 range:NSMakeRange(0, [str length])];
    // [match rangeAtIndex:1] gives the range of the group in parentheses
    // [str substringWithRange:[match rangeAtIndex:1]] gives the first captured group in this example
    

    【讨论】:

      【解决方案2】:

      您需要 RegexKitLite 库来执行正则表达式匹配:

      http://regexkit.sourceforge.net/RegexKitLite/

      之后,它几乎就像你在 PHP 中所做的一样。

      我将添加一些代码来帮助您:

      NSString *string     = @"stackoverflow.html";
      NSString *expression = @"stack(.*)\\.html";
      NSString *matchedString = [string stringByMatching:expression capture:1];
      

      ma​​tchedString 是@"overflow",应该正是你所需要的。

      【讨论】:

      • 我觉得 NSRegularExpression 更有用
      • 与 Perl 或 Ruby 或许多其他语言相比,NSRegularExpression 功能强大,但在最常见的情况下,它使用一个段落来完成一个句子的工作。我喜欢这个库示例如何让您匹配一个表达式并在一个合理的行中捕获一个组。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-13
      • 2020-07-19
      • 1970-01-01
      • 2012-08-07
      • 2013-05-09
      • 2020-07-17
      相关资源
      最近更新 更多