NSRegularExpression 匹配和替换为排除
NSRegularExpression matching and replacing with exclude
我正在开发一个小型 iOS 应用程序,但无法使用 NSRegularExpression class 创建模式。我需要一个模式,我可以用它来查找和匹配一个特殊的词并在以后替换它,但是我需要从匹配中排除这个词,以防它已经被这个匹配替换。因此,如果用户多次处理给定的文本,替换只会进行一次。
示例:
我需要查找所有给定文本中的所有 "yes"
并将其替换为 "probably yes"
。但是我需要排除 "probably yes"
中 "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
可能有人遇到过同样的问题。提前致谢
您可以使用negative look-behind
(?<!probably )yes
我正在开发一个小型 iOS 应用程序,但无法使用 NSRegularExpression class 创建模式。我需要一个模式,我可以用它来查找和匹配一个特殊的词并在以后替换它,但是我需要从匹配中排除这个词,以防它已经被这个匹配替换。因此,如果用户多次处理给定的文本,替换只会进行一次。
示例:
我需要查找所有给定文本中的所有 "yes"
并将其替换为 "probably yes"
。但是我需要排除 "probably yes"
中 "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
可能有人遇到过同样的问题。提前致谢
您可以使用negative look-behind
(?<!probably )yes