NSRegularExpression匹配并替换为exclude

时间:2016-05-21 08:17:32

标签: objective-c regex nsregularexpression

我正在使用一个小型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

可能是某人有同样的问题。提前致谢

1 个答案:

答案 0 :(得分:0)

您可以使用negative look-behind

(?<!probably )yes

<强> Regex Demo