【问题标题】:NSMutableString replaceOccurrencesOfString replacing whole wordsNSMutableString replaceOccurrencesOfString 替换整个单词
【发布时间】:2013-02-04 20:57:27
【问题描述】:

有没有办法使用replaceOccurrencesOfString(来自NSMutableString)来替换整个单词?

例如,如果我想替换字符串中所有出现的分数,比如“1/2”,我希望它只匹配那个特定的分数。所以如果我有“11/2”,我会希望它符合我的“1/2”规则。

我一直在尝试寻找这个问题的答案,但我没有运气。

【问题讨论】:

标签: ios objective-c nsmutablestring


【解决方案1】:

您可以将单词边界\b 与正则表达式一起使用。此示例匹配示例字符串开头和结尾的“1/2”,但不匹配中间选项

// Create your expression
NSString *string = @"1/2 of the 11/2 objects were 1/2ed in (1/2)";

NSError *error = nil;
NSRegularExpression *regex = 
  [NSRegularExpression 
    regularExpressionWithPattern:@"\\b1/2\\b"
                         options:NSRegularExpressionCaseInsensitive
                           error:&error];

// Replace the matches
NSString *modifiedString = 
[regex stringByReplacingMatchesInString:string
                                options:0
                                  range:NSMakeRange(0, [string length])
                           withTemplate:@"HALF USED TO BE HERE"];

【讨论】:

  • 谢谢!!这正是我想要的。
  • 没问题。不要忘记首先寻找简单的选项,因为通常最简单的选项通常是正确的(足够了)。如果空格是足够严格的分隔符,@H2CO3 的选项就会出现。
猜你喜欢
  • 1970-01-01
  • 2011-02-25
  • 2019-12-30
  • 1970-01-01
  • 2014-05-18
  • 1970-01-01
  • 1970-01-01
  • 2016-08-14
  • 1970-01-01
相关资源
最近更新 更多