gpt4 book ai didi

ios - 正则表达式中的多个 ????'s 导致错误

转载 作者:行者123 更新时间:2023-11-28 22:21:30 24 4
gpt4 key购买 nike

我有一个简单的正则表达式搜索和替换方法。一切都按预期工作正常,但是当我昨天进行锤子测试时,我输入的字符串有“????”在里面。这导致正则表达式失败并出现以下错误...

error   NSError *   domain: @"NSCocoaErrorDomain" - code: 2048  0x0fd3e970

经过进一步研究,我认为它可能会将问号视为“三字母”。 Chuck 在这篇文章中有很好的解释。 What does the \? (backslash question mark) escape sequence mean?

我试图在用这个创建正则表达式之前转义序列

string = [string stringByReplacingOccurrencesOfString:@"\?\?" withString:@"\?\\?"];

它似乎停止了错误,但搜索和替换不再有效。这是我正在使用的方法。

- (NSString *)searchAndReplaceText:(NSString *)searchString withText:(NSString *)replacementString inString:(NSString *)text {

NSRegularExpression *regex = [self regularExpressionWithString:searchString];
NSRange range = [regex rangeOfFirstMatchInString:text options:0 range:NSMakeRange(0, text.length)];

NSString *newText = [regex stringByReplacingMatchesInString:text options:0 range:range withTemplate:replacementString];

return newText;
}

- (NSRegularExpression *)regularExpressionWithString:(NSString *)string {

NSError *error = NULL;
NSString *pattern = [NSString stringWithFormat:@"\\b%@\\b", string];

NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:pattern options:NSRegularExpressionCaseInsensitive error:&error];

if (error)
NSLog(@"Couldn't create regex with given string and options");

return regex;
}

我的问题是;有没有更好的方法来逃避这个序列?这是三字母的情况,还是另一种可能性?或者在代码中是否有忽略三字母或关闭此功能的方法?

谢谢

最佳答案

My questions are; is there a better way of escaping this sequence?

是的,你可以适当escape any sequence of characters对于这样的正则表达式:

NSString* escapedExpression = [NSRegularExpression escapedPatternForString: aStringToEscapeCharactersIn];

编辑

您不必对整个表达式运行它。您可以使用 NSString stringwithFormat: 将转义字符串插入到带有模式的 RE 中,例如

pattern = [NSString stringWithFormat: @"^%@(.*)", [NSRegularExpression escapedPatternForString: @"????"]];

会给你模式 ^\?\?\?\?(.*)

关于ios - 正则表达式中的多个 ????'s 导致错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20270181/

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