edit 我澄清了IM存储在字符串中的文本。
所以这是我的正则表达式 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");
创建了一个正则表达式,但是您在代码中传递给正则表达式引擎的字符串@user hey heres my message: first message: and a second colon! haha
。
我假设您需要匹配像Text.. "@user hey heres my message: first message: and a second colon! haha"
这样的字符串。
请注意,ICU 正则表达式库不支持分支重置组。
我建议将分支重置组更改为具有交替组的捕获组:
^.*?:s+(.*?[!.?](?=s)|[^"]*).*$
查看正则表达式演示
详情:
^
- 字符串的开头.*?:
- 任何 0+ 字符,直到第一个:
后跟s+
- 1 个或多个空格...(.*?[!.?](?=s)|[^"]*)
- 第 1 组捕获.*?[!.?](?=s)
- 任何 0+ 字符尽可能少,直到第一个!
、.
或后跟空格的?
|
- 或[^"]*
- 除"
以外的零个或多个字符
.*$
- 字符串末尾的任何 0+ 字符
您只需访问组 1 即可获取所需的值。查看示例 Objective-C 演示。