gpt4 book ai didi

ios - NSMutableString replaceOccurrencesOfString 替换整个单词

转载 作者:可可西里 更新时间:2023-11-01 05:04:00 25 4
gpt4 key购买 nike

有没有办法使用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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com