【问题标题】:Search a pattern in a NSString [closed]在 NSString 中搜索模式 [关闭]
【发布时间】:2012-12-23 08:11:05
【问题描述】:

我想在一个字符串中搜索一个模式。在下面的代码中,模式字符串 '*' 可以是任何字符。

我从here 获得了这个示例代码,但它对我不起作用。

NSString *string;
NSString *pattern;
NSRegularExpression *regex;


string = @"img=img_1.png or it can be img=img.png";
pattern = @"img=*.png";

regex = [NSRegularExpression
         regularExpressionWithPattern:pattern
         options:NSRegularExpressionCaseInsensitive
         error:nil];

NSArray *matches = [regex matchesInString:string
                                  options:0
                                    range:NSMakeRange(0, [string length])];

NSLog(@"matches - %@", matches);

for (NSTextCheckingResult *match in matches)
{
    NSRange range = [match rangeAtIndex:1];
    NSLog(@"match: %@", [string substringWithRange:range]);
}

我希望 optput 字符串为 img_1.png & img.png

【问题讨论】:

    标签: iphone objective-c pattern-matching nsregularexpression


    【解决方案1】:

    将您的模式更改为:

    pattern = @"img=(.*?).png";
    

    【讨论】:

    • 我得到了这个 o/p -> 匹配:img_1.png 或者它可以是 img=img,我想要 img_1.png & img.png
    • 谢谢,解决了我的问题。
    【解决方案2】:

    这种模式可以很好地工作:

    NSString *pattern = @"(img=img[\\S]*\\.png)";
    

    匹配项是:

    0 : {0, 13} - img=img_1.png
    1 : {27, 11} - img=img.png
    

    用另一种模式:

    NSString *pattern = @"(img[^=][\\S]*png)";
    

    匹配项是(没有 img= 部分):

    0 : {4, 9} - img_1.png
    1 : {31, 7} - img.png
    

    【讨论】:

      猜你喜欢
      • 2023-03-05
      • 1970-01-01
      • 2012-06-01
      • 2011-03-08
      • 2014-01-09
      • 2013-04-26
      • 2013-02-13
      • 2014-12-27
      • 1970-01-01
      相关资源
      最近更新 更多