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

时间:2017-04-01 20:40:35

标签: ios objective-c regex nsstring

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

所以继承我的正则表达式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时,它总是返回nil并且我无法弄清楚它出错的地方,如果有人能帮我一把,我将不胜感激

预期输出

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

1 个答案:

答案 0 :(得分:1)

首先,您为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不支持Branch Reset Groups

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

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

请参阅regex demo

<强>详情:

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

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