• iOS谓词匹配字符串以及替换


    1.判断某个字符串是否符合某个正则表达式,通常用这个方法:

    // 判断字符串首字符是否为字母
    NSString *string = @"wo";
    // 1、准备正则式
    NSString *regex = @"^[A-Za-z]*$"; // 只能是字母,不区分大小写
    // 2、拼接谓词
    NSPredicate *predicateRe1 = [NSPredicate predicateWithFormat:@"self matches %@", regex];
    // 3、匹配字符串
    BOOL resualt = [predicateRe1 evaluateWithObject:string];
    NSLog(@"匹配结果%d", resualt);

    2.但是我们开发过程中也有可能遇到这种需求,匹配字符串并且找出符合正则的字符,并替换成其他的字符显示出来,这种情况下可以用这个方法:

    NSString *string = textField.text;

     // 1、准备正则式

        NSString *regex = @"[^\x00-\xff]|[{}()/]";

        

        NSString * replacement = @"";

        //    // 创建 NSRegularExpression 对象,匹配 正则表达式

        NSRegularExpression *regExp = [[NSRegularExpression alloc] initWithPattern:regex

                                                                           options:NSRegularExpressionCaseInsensitive

                                                                             error:nil];

        NSString *resultStr = string;

        // 替换匹配的字符串为 searchStr

        resultStr = [regExp stringByReplacingMatchesInString:string

                                                     options:NSMatchingReportProgress

                                                       range:NSMakeRange(0, string.length)

                                                withTemplate:replacement];

        NSLog(@"\nsearchStr = %@\nresultStr = %@",string,resultStr);

        textField.text = resultStr;

  • 相关阅读:
    log4j 配置文件
    log4j安装与简介
    tomcat服务
    查看系统网络连接打开端口、系统进程、DOS打开文件
    find查找指定类型文件并删除
    git/github在windows上使用
    VIM配置自动提示功能
    VIM Taglist安装配置和使用
    python Scipy积分运算大全(integrate模块——一重、二重及三重积分)
    python matplotlib绘图大全(散点图、柱状图、饼图、极坐标图、热量图、三维图以及热图)
  • 原文地址:https://www.cnblogs.com/cui-cui/p/7512846.html
Copyright © 2020-2023  润新知