编辑我明确说明了我将存储在字符串中的文本。
这是我的正则表达式 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 嘿,这是我的消息:第一条消息:和第二个冒号!哈哈
.
我假设您需要匹配像 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+
- 1 个或多个空格...(.*?[!.?](?=\s)|[^"]*)
- 第 1 组捕获.*?[!.?](?=\s)
- 任何 0+ 个字符,尽可能少,直到第一个!
,。
或?
后跟空格|
- 或者[^"]*
-"
以外的零个或多个字符
.*$
- 到字符串末尾的任何 0+ 个字符
您只需访问第 1 组即可获得所需的值。查看示例 Objective-C demo .
关于ios - 我的正则表达式在 obj-c 中每次都返回 nil,包括示例代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43161788/