【发布时间】:2017-08-26 23:18:47
【问题描述】:
编辑我澄清了我在字符串中存储的确切文本。
所以这是我的正则表达式https://regex101.com/r/fWFRya/5 - 这有错误的字符串 zz,这就是为什么每个人都对我的错误感到困惑,现在又修复了
^.*?".*?:\s+(?|(?:(.*?[!.?])\s+.*?)|(.*?))".*$
这是它在我的代码中的外观,反斜杠添加到转义引号
NSString *regexTweet = @"^.*?\".*?:\\s+(?|(?:(.*?[!.?])\\s+.*?)|(.*?))\".*$";
//the example string contains the text> @user hey heres my message: first message: and a second colon! haha.
NSString *example1 = @"@user hey heres my message: first message: and a second colon! haha.";
NSError *regexerror = nil;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:regexTweet options:NSRegularExpressionCaseInsensitive error:®exerror];
NSRange range = [regex rangeOfFirstMatchInString:example1
options:0
range:NSMakeRange(0, [example1 length])];
NSString *final1 = [example1 substringWithRange:range];
HBLogDebug (@"example 1 has become %@", final1);
当我登录 final1 时,它总是返回 nil,我无法弄清楚哪里出了问题,如果有人能帮我一把,我将不胜感激
预期输出为
第一条消息:和第二个冒号!
【问题讨论】:
-
将示例行更改为
NSString *example1 = @"\"@user hey heres my message: first message: and a second colon! haha.\"";,它应该可以工作。检查您的引擎是否支持分支重置构造(?|..)如果不支持,则它不是真正需要的,并且可以将其作为一个集群组来完成^.*?".*?:\s+(?:(?:(.*?[!.?])\s+.*?)|(.*?))".*$答案只是$1$2的串联,因为只有一个组可以包含一个字符串。这将保持您现在正在做的修剪完好无损。 -
@sln 我在那个正则表达式链接中有错误的字符串(我在这里修复它时忘记更改它),你能再检查一下吗?对不起
-
您可能有心理障碍。正则表达式只会匹配包含 2 个双引号的字符串。要制作语言字符串,必须对这些引号进行转义。
string var = " <- begin of string, quote 1 \" and quote 2 \" end of string ->";
标签: ios objective-c regex nsstring