我的正则表达式在 obj-c 中每次都返回 nil,包括示例代码

My regex is returning nil everytime in obj-c, example code included

编辑我明确说明了我将存储在字符串中的文本。

这是我的正则表达式 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:&regexerror];

  NSRange range = [regex rangeOfFirstMatchInString:example1
  options:0
  range:NSMakeRange(0, [example1 length])];
  NSString *final1 = [example1 substringWithRange:range];
  HBLogDebug (@"example 1 has become %@", final1);

当我登录 final1 时,它总是 returns 零,我无法弄清楚哪里出了问题,如果有人能帮助我,我将不胜感激

预期输出为

第一条消息:和第二个冒号!

首先,您为 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 regex library does not support Branch Reset Groups.

我建议将分支重置组更改为带有交替组的捕获组

^.*?:\s+(.*?[!.?](?=\s)|[^"]*).*$

regex demo

详情:

  • ^ - 字符串的开头
  • .*?: - 任何 0+ 个字符,直到第一个 : 后跟
  • \s+ - 1 个或多个空格...
  • (.*?[!.?](?=\s)|[^"]*) - 第 1 组捕获
    • .*?[!.?](?=\s) - 任何 0+ 个字符尽可能少,直到第一个 !.? 后跟空格
    • | - 或
    • [^"]* - "
    • 以外的零个或多个字符
  • .*$ - 字符串末尾的任何 0+ 个字符

您只需访问第 1 组即可获取所需的值。查看示例 Objective-C demo.