美文网首页
iOS 正则表达式匹配子串

iOS 正则表达式匹配子串

作者: Ever_Blacks | 来源:发表于2018-01-08 11:54 被阅读514次

在工程中需要从 protocol://customProtocol|title=this is title|message=this is message|shareUrl=this is url 字符串中分别拿到 title、message、shareUrl 的内容,因为字符串的格式是固定的,自然而然的想到了正则表达式, 当然也可以对字符串按照 | 分隔,然后再按 = 分隔之后获取指定的值。

最终实现代码:

    NSString *testStr = @"protocol://customProtocol|title=this is title|message=this is message|shareUrl=this is url";
    NSString *parten = @"\\|title=(.*?)\\|message=(.*?)\\|shareUrl=(.*)$";
    NSError *error = nil;
    NSRegularExpression *reg = [NSRegularExpression regularExpressionWithPattern:parten options:NSRegularExpressionCaseInsensitive error:&error]; //options 根据自己需求选择
    
    NSArray *matches = [reg matchesInString:testStr options:NSMatchingReportCompletion range:NSMakeRange(0, testStr.length)];

    for (NSTextCheckingResult *match in matches) {
        //NSRange matchRange = [match range]; //获取所匹配的最长字符串
        for (int i = 0; i < match.numberOfRanges; i++) {
            NSRange matchRange = [match rangeAtIndex:i];
            NSString *matchString = [testStr substringWithRange:matchRange];
            NSLog(@"index:%@, %@", @(i) matchString);
        }
    }
    
    output:
    index:0, |title=this is title|message=this is message|shareUrl=this is url
    index:1, this is title
    index:2, this is message
    index:3, this is url
    

实际开发过程中遇到的坑:

  • | 在正则表达式中是元字符,所以在写parten 中需要用 \ 转义字符, 但在OC中 \ 也是转义字符,所以最后需要 \\| 来表示匹配 |
  • 正则默认是贪心的,所以需要在 .* 后加上 ? 正则表达式re中的贪心算法和非贪心算法
  • 注意NSTextCheckingResultnumberOfRanges的用法。 rangeAtIndex 为0 是匹配最长的结果。

A result must have at least one range, but may optionally have more (for example, to represent regular expression capture groups). The range at index 0 always matches the range property. Additional ranges, if any, will have indexes from 1 to numberOfRanges-1. rangeWithName: can be used with named regular expression capture groups.

最后推荐一个比较友好的正则表达式在线测试网站Oneline regex test

相关文章

  • kmp_algorithm

    tips:kmp算法分两个步骤:1)计算子串的next数组2)匹配子串conclusion:其实求next数组和匹...

  • iOS 正则表达式匹配子串

    在工程中需要从 protocol://customProtocol|title=this is title|mes...

  • 2018年7月3日【Python学习笔记】

    一、正则表达式 正则表达式主要用于字符串查找‘匹配、分割 import re match(正则表达式字符串,需要匹...

  • Python 学习笔记 060

    正则表达式 02 正则表达式 的高级用法 字符串的高级使用 正则表达式中的重复 匹配多个字符串 通过正则表达式 匹...

  • JavaScript正则表达式

    一、认识正则表达式 正则表达式是描述字符模式的对象,正则表达式用于对字符串模式匹配及检索替换,是对字符串执行模式匹...

  • Python 中正则表达式全部语法速查

    正则表达式 正则语法 特性 正则表达式可以拼接,如果A和B都是正则表达式,那么 AB也是正则表达式.如果字符串p匹...

  • Java正则表达式的语法与示例

    1匹配验证-验证Email是否正确 2在字符串中查询字符或者字符串 3常用正则表达式 规则 正则表达式语法一个或...

  • KMP中的next数组

    KMP算法首先要构造匹配子串的数组。假设有两个字符串,一个是待匹配的字符串,一个是要查找的匹配子串。现在我们要在中...

  • 谓词和正则表达式

    正则表达式 iOS中,通过传入正则表达式字符串,获取到NSRegularExpression对象,使用matche...

  • 正则表达式语法

    正则表达式(Regular Expression)是一种字符串匹配的模式,可以用来检查一个串是否含有某种子串、将匹...

网友评论

      本文标题:iOS 正则表达式匹配子串

      本文链接:https://www.haomeiwen.com/subject/bytbnxtx.html