ios - NSMutableString replaceOccurrencesOfString 替换整个单词

标签 ios objective-c nsmutablestring

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

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

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

最佳答案

您可以在 Regex 中使用单词边界 \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"];

关于ios - NSMutableString replaceOccurrencesOfString 替换整个单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14695493/

相关文章:

objective-c - iPhone 号码文本到完整的货币等式

ios - 无法将类型 'QuerySnapshot?' 的值转换为预期的参数类型 'DataSnapshot'

objective-c - 如何从协议(protocol)方法描述列表中解密 "objc_method_description"?

objective-c - 如何从另一个字符串替换 NSMutableString 中出现的字符串

ios - iOS 中 SQLite 数据库的电子邮件 CSV

ios - Xcode 10.2.1 界面生成器 - 无法在 View Controller (或文档大纲)上移动(拖动)UI 元素

iphone - 如何将一个 AlertView 与另一个 AlertView 一起显示

objective-c - 使用从 UIImagePickerController 保存的图像进行内存管理

ios - 将输入的数字格式化为美国电话号码以格式化 (###) ###-####

iphone - 解析 xml 时 NSCFString appendString 泄漏