【问题标题】:Replace occurences of string that contains any number替换出现的包含任意数字的字符串
【发布时间】:2011-11-16 10:03:13
【问题描述】:

假设我有一个包含控制代码“\f3”的字符串(是的,它是 RTF)。我想用另一个字符串替换那个控制代码。目前我正在使用[mutableString replaceOccurrencesOfString:@"\f3" withString:@"replacement string" options:0 range:NSMakeRange(0, [mutableString length])];

这很好用,但是有时代码可以是“\f4”甚至是“\f12”。如何替换这些字符串?我可以为每个使用replaceOccurrencesOfString,但更好的方法是使用通配符,因为它可以是任何数字。

【问题讨论】:

    标签: ios string


    【解决方案1】:

    正则表达式可以做到这一点。

    查看NSRegularExpression (iOS >= 4) 和this page 了解正则表达式的工作原理。

    你会想要这样的:

    // Create your expression
    NSError *error = nil;
    NSRegularExpression *regex = 
      [NSRegularExpression regularExpressionWithPattern:@"\\b\f[0-9]*\\b"
                                                options:NSRegularExpressionCaseInsensitive
                                                  error:&error];
    
    // Replace the matches
    NSString *modifiedString = [regex stringByReplacingMatchesInString:string
                                                           options:0
                                                             range:NSMakeRange(0, [string length])
                                                      withTemplate:@"replacement string"];
    

    警告:我还没有测试过我的正则表达式,而且我在第一次就正确的情况下并不擅长;我只知道正则表达式是你前进的方向,它必须看起来像 something ;)

    【讨论】:

    • 太棒了!这正是我一直在寻找的。我认为这与正则表达式有关,但直到现在一直避免使用它们!看来我得好好学习了。
    猜你喜欢
    • 2017-11-24
    • 1970-01-01
    • 2011-03-10
    • 1970-01-01
    • 2021-06-08
    • 2020-05-13
    • 2017-04-09
    • 2014-03-30
    • 2016-12-24
    相关资源
    最近更新 更多