【问题标题】:NSRegularExpression matching and replacing with excludeNSRegularExpression 匹配并替换为 exclude
【发布时间】:2016-05-21 16:22:11
【问题描述】:

我正在开发一个小型 iOS 应用程序,并且无法使用 NSRegularExpression 类创建模式。我需要一个可以用来查找和匹配特殊单词并稍后替换它的模式,但我需要从匹配中排除这个单词,以防它已经被这个匹配替换。因此,如果用户多次处理给定的文本,则替换只会进行一次。

例子:

我需要在任何给定文本中查找所有"yes" 并将其替换为"probably yes"。但我需要排除 "yes""probably yes" 中的替换,以防用户再处理一次文本,所以它看起来不像 "probably probably yes"

NSRegularExpression *regexYesReplace = [NSRegularExpression regularExpressionWithPattern:@"some pattern" options:0 error:&error];
NSString *replacementStringYesReplace = @"probably yes";
replacedText = [regexYesReplace stringByReplacingMatchesInString:afterText options:options range:range withTemplate:replacementStringYesReplace];

我尝试从这个问题中实现模式并修复 NSRegularExpression 的语法,但没有成功。

Regex replace text but exclude when text is between specific tag

可能有人遇到了同样的问题。提前致谢

【问题讨论】:

  • 简单的解决方案:生成一个不属于字符串的随机占位符(例如!F4E67O!,生成一个新占位符,直到它不包含在内)。将所有probably yes 替换为占位符,然后将所有yes 和占位符替换为probably yes

标签: objective-c regex nsregularexpression


【解决方案1】:

你可以使用negative look-behind

(?<!probably )yes

Regex Demo

【讨论】:

    猜你喜欢
    • 2012-07-07
    • 2010-10-29
    • 2012-02-15
    • 2013-11-09
    • 2014-04-21
    • 2022-01-18
    • 2014-05-25
    • 1970-01-01
    相关资源
    最近更新 更多